我通过应用程序执行存储过程时SQL Server会引发超时,但是当我在Management Studio

时间:2017-01-19 13:41:08

标签: sql sql-server node.js

我有一个类似这样的存储过程:

PROCEDURE [dbo].[myStoredProcedure]
 @period varchar(7),
 @pgSize int,
 @pg int,
 @sort varchar(50)
AS
BEGIN
    DECLARE @exec nvarchar(1000)
    DECLARE @order varchar(100)
    DECLARE @where varchar(100)

    CREATE TABLE #temp (
        fieldOne varchar(7),
        fieldTwo varchar(7),
        fieldThree int,
        fieldFour varchar(7)
    )   

    If exists(select 1 from tableA Where date = @period)
    Begin
        INSERT INTO #temp
        SELECT DISTINCT a.fieldOne, b.fieldTwo, td.fieldThree, b.fieldFour
        FROM tableA a
        LEFT JOIN docType td ON td.code = a.docType
        INNER JOIN tableB b ON a.code = b.code
        AND b.state= 'A'
        AND a.date = convert(int, @period);
    END
    ELSE
    BEGIN
        INSERT INTO #temp
        SELECT DISTINCT a.fieldOne, b.fieldTwo, td.fieldThree, b.fieldFour
        FROM tableAHistoric a
        LEFT JOIN docType td ON td.code = a.docType
        INNER JOIN tableBHistoric b ON a.code = b.code
        AND b.state= 'A'
        AND a.date = convert(int, @period);
    END

    -- Eliminate registers such that there is another register with the same fieldOne but different fieldTwo, and keep the one that has smaller fieldThree or,
    -- in case they are equal, keep the one with smallest fieldFour
    DELETE t1
    FROM #temp t1
    INNER JOIN #temp t2 ON t1.fieldOne = t2.fieldOne AND t1.fieldTwo <> t2.fieldTwo
    WHERE t1.fieldThree > t2.fieldThree OR (t1.fieldThree = t2.fieldThree AND t1.fieldFour > t2.fieldFour)

    SET @order = ' order by ' + CASE LEFT(@sort, 1) WHEN '-' THEN SUBSTRING(@sort, 2, LEN(@sort) - 1) + ' desc' ELSE @sort END 

    IF @pg = 1
    BEGIN
        SET @exec = CONCAT(
                'select * from #temp ', 
                @order, 
                ' offset (@pg-1) * @pgSize rows  fetch next @pgSize rows only '
                )

        EXEC sp_executesql @exec, N'@pg int, @pgSize int', @pg = @pg, @pgSize = @pgSize
        SELECT rows = COUNT(*) FROM #temp
    END
    ELSE
    BEGIN
        SET @exec = CONCAT(
                'select * from #temp ', 
                @order, 
                ' offset (@pg-1) * @pgSize rows  fetch next @pgSize rows only '
                )
        EXECUTE sp_executesql @exec, N'@pg int, @pgSize int', @pg = @pg, @pgSize = @pgSize
    END 

如果我使用以下参数从SQL Server Management Studio查询:

EXEC myStoredProcedure '201603', 10, 1, 'fieldOne'

它会在一秒钟内返回。

如果我在变量@period中硬编码'201603'并从我的Node.js应用程序执行存储过程,它也会在一秒内返回。

但是,如果我在通过Node.js应用程序执行存储过程时传递该参数,则会出现超时。我注册了存储过程要么永远不会执行INSERT,要么永远不会在超时之前完成。超时设置为15秒,我将其设置为2分钟进行测试,但结果是相同的:超时。有趣的是它只发生在那个价值:'201603'。结果应返回889个寄存器。我已经使用返回200个结果的其他值测试了它,它们没有问题。

作为参考,字段date是一个整数。但即使我在@period子句中转换参数WHERE,也没有任何变化。

可能是什么问题?我该怎么看?

感谢。

1 个答案:

答案 0 :(得分:1)

它可能是一个缓存的执行计划。

尝试在SP底部添加“OPTION(RECOMPILE)”