2014-10-28 91 views
1

我需要將subquery結果存儲在變量中,並將其用於主查詢中以節省查詢的執行時間,否則我必須再次爲此寫入相同的subquery。下面的代碼給出:如何將子查詢結果存儲在變量中並在主查詢中使用

select DISTINCT 
convert(datetime,substring(o.TransactTime, 0,9), 112) + CONVERT(datetime, substring(o.transacttime,10,LEN(o.transacttime)), 114), 
o.clordid, 
ack.strategyid, 
o.Account, 
o.AllocAccount, 
o.symbol, 
o.price, 
ISNULL((Select Top 1 L.orderqty from order_msgs_incoming1 L where o.clordid=L.clordid and L.msg_id in (17,18,19,22,59,44) order BY L.transacttime DESC),o.orderqty) orderqty, 

o.InClOrdID, 
(SELECT ISNULL(ISNULL((Select Top 1 L.orderqty from order_msgs_incoming1 L where o.clordid=L.clordid and L.msg_id in (17,18,19,22,59,44) order BY L.transacttime DESC),o.orderqty)-sum(ex.LastShares),ISNULL((Select Top 1 L.orderqty from order_msgs_incoming1 L where o.clordid=L.clordid and L.msg_id in (17,18,19,22,59,44) order BY L.transacttime DESC),o.orderqty)) from order_msgs_incoming<TblIndx> ex where 
    o.Clordid = ex.clordid 
) RemainingQuantity 
from order_msgs_incoming1 o 
/*picking ack rows to update strategyId since StrategyId is null for 43 but populated for 46*/ 
left outer join order_msgs_incoming1 ack on o.clordid = ack.clordid and ack.msg_id=46 
where 
/*row for new order only since that contains all columns values*/ 
o.msg_id = 43 

我需要這樣的

select DISTINCT 
variableValue=ISNULL((Select Top 1 L.orderqty from order_msgs_incoming1 L where o.clordid=L.clordid and L.msg_id in (17,18,19,22,59,44) order BY L.transacttime DESC),o.orderqty) orderqty, 

o.InClOrdID, 
(SELECT ISNULL(variableValue-sum(ex.LastShares),variableValue) from order_msgs_incoming<TblIndx> ex where 
    o.Clordid = ex.clordid 
) RemainingQuantity 
from order_msgs_incoming1 o 

請幫助我。

回答

0

您可以聲明一個變量並使用SELECT子句爲其分配一個值。然後在主查詢中使用該變量。請看以下代碼:

DECLARE @variableValue bit; 

SELECT @variableValue = ISNULL(
         (
         SELECT TOP 1 L.orderqty 
         FROM order_msgs_incoming1 L 
         WHERE o.clordid=L.clordid 
         AND L.msg_id in (17,18,19,22,59,44) 
         ORDER BY L.transacttime DESC 
         ) 
         ,o.orderqty 
        ) 
FROM order_msgs_incoming1 o 

SELECT DISTINCT 
@variableValue AS orderqty, 
o.InClOrdID, 
(
    SELECT ISNULL(variableValue-sum(ex.LastShares) 
    ,variableValue) 
    FROM order_msgs_incoming<TblIndx> ex 
    WHERE o.Clordid = ex.clordid 
) RemainingQuantity 
FROM order_msgs_incoming1 o 

您也可以使用下面的代碼,以改變的子查詢,這樣就可以使用它在一個變量:

SELECT TOP 1 L.orderqty 
FROM order_msgs_incoming1 L 
INNER JOIN order_msgs_incoming1 o 
    ON o.clordid=L.clordid 
    AND L.msg_id in (17,18,19,22,59,44) 
ORDER BY L.transacttime DESC 
+0

嘿,我不走子查詢結果在單獨的查詢中,並在其他查詢中使用相同。想要將結果帶入變量並在主查詢中使用。 – 2014-10-28 06:28:12

+0

@NeerajDubey我不明白你的觀點。你不能在一個單獨的查詢中得到「子查詢結果」,如果它是標量,它必須在表中或變量中。我想我已經做了你想要的同樣的事情。 「orderqty」列的值現在從變量「variableValue」中填充。 – Vaibhav 2014-10-28 06:54:28

相關問題