Sql-Server-2008
儲存過程永遠執行,但內部查詢執行良好
如果我執行
exec pr_BuscaLog -2
,它將永遠執行(幾天,沒有盡頭)。但是,如果我只是複制查詢並自行執行,它會在幾秒鐘內執行。
更新統計數據沒有幫助。
--pr_BuscaLog -1 CREATE procedure [dbo].[pr_BuscaLog] (@qtdDias int) as begin declare @cmd as nvarchar(4000) declare @banco as varchar(100) declare @dataLimite as datetime
更新:當我執行時
EXEC PR_BUSCALOG
,它開始執行,然後停止。
僅通過檢查程式碼很難判斷它是否由於無限循環或阻塞而永遠執行 - 我的猜測是後者。但這裡有一種稍微不同的方法,可以避免一些可能有問題的事情:
CREATE PROCEDURE dbo.pr_BuscaLog @qtdDias INT AS BEGIN SET NOCOUNT ON; DECLARE @cmd NVARCHAR(MAX) = N'', @dataLimite DATETIME = CONVERT(SMALLDATETIME, DATEADD(DAY, @qtdDias, GETDATE())); SELECT name INTO #tmp FROM sys.databases WHERE database_id > 4; -- delete the ones that don't have that view SELECT @cmd += N'DELETE #tmp WHERE name = N''' + name + ''' AND NOT EXISTS (SELECT 1 FROM ' + QUOTENAME(name) + '.sys.views WHERE name = N''vwLogProjetos'');' FROM #tmp EXEC sys.sp_executesql @cmd; SET @cmd = N''; SELECT @cmd += N'INSERT PainelControle..tblLogProjetos(...columns...) select ...columns... FROM ' + QUOTENAME(name) + N'.dbo.vwLogProjetos as T1 with (nolock) where DtTrabalho >= @dt and not exists ( select 1 from PainelControle.dbo.tblLogProjetos T2 Where t2.BancoDados collate SQL_Latin1_General_CP1_CI_AS = t1.BancoDados collate SQL_Latin1_General_CP1_CI_AS and t2.codlog = t1.codlog );' FROM #tmp; BEGIN TRY EXEC sys.sp_executesql @cmd, N'@dt DATETIME', @dataLimite; END TRY BEGIN CATCH insert into dbo.tblLogProjetosErro (rotina, comando,Data) values ('pr_BuscaLog', @cmd + ERROR_MESSAGE(), GETDATE()); END CATCH END
我改變了一些東西(或者你應該改變):
while 循環中的 select 語句
Select count(1) from #tmp
實際上是一個常量值。換句話說,它不會在每次循環中都發生變化。我猜你真的想每個數據庫循環一次,所以你需要修改你的
while
循環。