将 MS Sql 结果设置为变量并重用它

2021-09-10 00:00:00 sql tsql sql-server

目前我的代码是这样的.

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.

相关文章