問題描述
目前我的代碼是這樣的.
Currently my code is something like this.
select *
from tblReq
where ReqID in (select ReqID from tblLog where LogDate >= '2015/04/01' and LogDate < '2015/05/31')
只是想知道數據庫實際上是如何找到這個查詢的結果的?每次在子查詢中運行時都會重新運行嗎?是否有任何腳本可以將結果列表存儲在某個變量中并能夠重新使用它?(以下代碼)
Just wondering how actually the database find the result for this query? Is it re-run every time it ran in sub-query? And is there any script where I can store the list of result in some variable and able to use it back? (below code)
select @logs = tblLog.ReqID from tblLog where tblLog.LogDate >= '2015/04/01' and tblLog.LogDate < '2015/05/31'
select * from tblReq where ReqID in (@logs)
推薦答案
是的,您可以將結果存儲在變量中并在以后多次重復使用.在您的情況下,它將是一個 table 變量
,因為您可以有多個項目.然后,簡單的 join
到初始查詢:
Yes, you can store the result in a variable and reuse it several times later. In your case, it will be a table variable
as you could have multiple items. Then, simple join
it to the initial query:
DECLARE @Logs TABLE
(
[LogID] INT
);
INSERT INTO @Logs ([LogID])
Select tblLog.ReqID
from tblLog
where tblLog.LogDate >= '2015/04/01'
and tblLog.LogDate < '2015/05/31'
select *
from tblReq A
INNER JOIN @Logs L
ON A.ReqID = L.LogID
此外,這可能會損害您的查詢性能,因為表變量不像查詢優化器的黑匣子
.如果您要存儲大量行,請改用 temporary
表以使用并行執行計劃.
Also, this could harm your query performance, as table variables are not like black box
for the query optimizer. If you are storing a large amount of rows, use temporary
tables instead in order to use parallel execution plans.
這篇關于將 MS Sql 結果設置為變量并重用它的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!