在这个SQL存储过程中真的需要临时表吗?

时间:2015-05-05 15:55:05

标签: sql-server tsql stored-procedures

在看到我参与的一个项目中的一些现有的sprocs时,我看到的是这样的事情:

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;

我这里最突出的是他们正在使用临时表,而我真的没有看到这种类型的sproc的好处。临时表中没有添加新字段(没有表的组合),只有tbl_patientBiometricResults表中可用字段的一部分。

在这种情况下使用临时表是否有好处?

2 个答案:

答案 0 :(得分:1)

它确实看起来有点过度,但我发现在某些情况下,例如涉及SSIS,您可能需要构造一个这样的表变量,以便SSIS包能够识别存储过程返回的元数据。不确定这在你的情况下是否重要!

答案 1 :(得分:1)

正如Sean在评论中提到的,使用表变量没有任何好处。您可以轻松地以更简单的格式重写查询:

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
相关问题