Sql server 在这个SQL存储过程中确实需要临时表吗?
通过查看我参与的项目中的一些现有存储过程,我看到了如下情况:Sql server 在这个SQL存储过程中确实需要临时表吗?,sql-server,tsql,stored-procedures,Sql Server,Tsql,Stored Procedures,通过查看我参与的项目中的一些现有存储过程,我看到了如下情况: declare @tmpTable Table ( ID bigint, patientID uniqueidentifier, resultDate datetime, resultParameter nvarchar(50), resultValue decimal(18, 6), resultUnit nvarchar(50), pos smallint,
declare @tmpTable Table (
ID bigint,
patientID uniqueidentifier,
resultDate datetime,
resultParameter nvarchar(50),
resultValue decimal(18, 6),
resultUnit nvarchar(50),
pos smallint,
minpos smallint,
maxpos smallint
)
if (@patientID is not null)
begin
declare @minpos smallint = 0;
declare @maxpos smallint = 0;
select
@minpos = min(a.pos),
@maxpos = max(a.pos)
from tbl_patientBiometricResults a (nolock)
where a.patientID = @patientID
insert into @tmpTable
(
ID,
patientID,
resultDate,
resultParameter,
resultValue,
resultUnit,
pos,
minpos,
maxpos
)
select
a.ID,
a.patientID,
a.resultDate,
a.resultParameter,
a.resultValue,
a.resultUnit,
a.pos,
@minpos,
@maxpos
from tbl_patientBiometricResults a (nolock)
where a.patientID = @patientID
end
select * from @tmpTable order by pos;
我在这里最突出的一点是他们使用临时表,我真的看不到这种存储过程的好处。临时表中没有添加新字段(没有表的组合),只有tbl\u patientBiometricResults
表中可用的字段子集
在这种情况下使用临时表有好处吗
在上下文之外,这似乎有些过分,但我发现在某些情况下,例如涉及SSI的情况下,您可能需要构造这样的表变量,以便SSIS包识别存储过程返回的元数据。但我不确定这对你来说是否重要 正如肖恩在评论中提到的,使用表变量没有任何好处。您可以轻松地用以下更简单的格式重写查询:
IF (@patientID is not null)
BEGIN
SELECT ID,
patientID,
resultDate,
resultParameter,
resultValue,
resultUnit,
pos,
minPos, --MIN(pos) OVER (PARTITION BY NULL) /*Alternative for SQL 2012+. No need for CROSS APPLY*/
maxPos --MAX(pos) OVER (PARTITION BY NULL)
FROM tbl_patientBiometricResults
CROSS APPLY(
SELECT MIN(pos) minPos,
MAX(pos) maxPos
FROM tbl_patientBiometricResults
WHERE patientID = @patientID
)
WHERE patientID = @patientID
ORDER BY pos;
END
这是一个表变量,不是临时表。从这里我看到,不需要这个变量。而且,我会把诺洛克除掉