在变量中设置MS Sql结果并重用它
目前我的代码是这样的在变量中设置MS Sql结果并重用它,sql,sql-server,tsql,Sql,Sql Server,Tsql,目前我的代码是这样的 select * from tblReq where ReqID in (select ReqID from tblLog where LogDate >= '2015/04/01' and LogDate < '2015/05/31') 只是想知道数据库是如何找到这个查询的结果的?它是否每次在子查询中运行时都重新运行?是否有脚本可以将结果列表存储在某个变量中并可以使用它?以下代码 select @logs = tblLog.ReqID from tblL
select *
from tblReq
where ReqID in (select ReqID from tblLog where LogDate >= '2015/04/01' and LogDate < '2015/05/31')
只是想知道数据库是如何找到这个查询的结果的?它是否每次在子查询中运行时都重新运行?是否有脚本可以将结果列表存储在某个变量中并可以使用它?以下代码
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)
如果以后要引用查询,可以创建
CREATE VIEW V1 AS
SELECT tblLog.ReqID
FROM tblLog
WHERE tblLog.LogDate >= '2015/04/01'
AND tblLog.LogDate < '2015/05/31'
是的,您可以将结果存储在变量中,并在以后多次重用它。在您的情况下,它将是一个表变量,因为您可以有多个项。然后,简单地将其连接到初始查询:
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
此外,这可能会损害查询性能,因为表变量不像查询优化器的黑盒。如果要存储大量行,请使用临时表,以便使用并行执行计划。对于您的情况。。最好的解决方案是使用联接 即使在复杂的情况下也能工作的最好方法是,它包括一个查询tabletblog
select * from tblReq join (select logid from tbllog where
tblLog.LogDate >= '2015/04/01' and tblLog.LogDate < '2015/05/31')tblLog
on tblReq.ReqID=tblLog.ReqID
还是简单
select * from tblReq join tblLog on tblReq.ReqID=tblLog.ReqID where
tblLog.LogDate >= '2015/04/01' and tblLog.LogDate < '2015/05/31'
或者更简单:也可以使用子查询子查询更简单,但如果得到太多结果,则会降低性能
select * from tblReq where ReqID in (select tblLog.ReqID from tblLog where
tblLog.LogDate >= '2015/04/01' and
tblLog.LogDate < '2015/05/31')
如果您必须存储,因为您在同一过程中多次使用它,那么
craete TABLE #logs
(
[LogID] INT
);
insert into #logs select tblLog.ReqID from tblLog where
tblLog.LogDate >= '2015/04/01' and
tblLog.LogDate < '2015/05/31'
select * from tblReq where ReqID in (select logid from #logs) // or use join
重要的
变量存储单个值。临时表存储完整的表。对于遍历临时表或其他表的行,有游标。不过,请尝试使用别担心,SQL server通常会为单个语句选择最佳的查询计划。使用任何类型的临时表或变量通常都会使事情变得更慢——当然也有例外,但对于那些简单的查询来说则不然。查看SSM中的执行计划并自行决定:变量存储单个值。临时表存储完整的表。对于在临时表行或其他行中进行迭代,有游标,创建这样的视图毫无意义,因为它可以重新写入接受开始和结束日期作为参数的内嵌函数参数化视图。+1这是我通常采用的方法。然而,我可能不会加入到表中,而是像这样使用它;其中ReqID在SELECT LogID FROM@Logs中。不过,我会纯粹从可读性的角度出发,而不是从性能的角度出发。
craete TABLE #logs
(
[LogID] INT
);
insert into #logs select tblLog.ReqID from tblLog where
tblLog.LogDate >= '2015/04/01' and
tblLog.LogDate < '2015/05/31'
select * from tblReq where ReqID in (select logid from #logs) // or use join