[英]SQL Server throws timeout when I execute a stored procedure through an application, but not when I execute it in the Management Studio
我有一个存储过程是这样的:
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
是整数。 但是,即使我在WHERE
子句中转换了@period
参数,也没有任何改变。
可能是什么问题呢? 我应该看什么?
谢谢。
它可能是一个缓存的执行计划。
尝试在SP的底部添加“ OPTION(RECOMPILE)”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.