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

Set MS Sql result in variable and reuse it(将 MS Sql 结果设置为变量并重用它)
本文介绍了将 MS Sql 结果设置为变量并重用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我的代码是这样的.

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 结果设置为变量并重用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)