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

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

相关文档推荐

Creating table with T-SQL - can#39;t see created tables in Object explorer(使用 T-SQL 创建表 - 在对象资源管理器中看不到创建的表)
How to check if VARCHAR strings are (not) hexadecimal?(如何检查 VARCHAR 字符串是否为(非)十六进制?)
Arithmetic overflow error converting IDENTITY to data type int(将 IDENTITY 转换为数据类型 int 的算术溢出错误)
Where clause if there are multiple of the same ID(如果有多个相同的 ID,Where 子句)
Azure SQL: Invalid Object Name using Powershell#39;s quot;Invoke-sqlcmdquot; on Adventureworks(Azure SQL:使用 Powershell 的“Invoke-sqlcmd的无效对象名称在 Adventureworks 上)
How to Convert Table Data into xml format using sql with multiple sub nodes(如何使用具有多个子节点的sql将表数据转换为xml格式)