2015-05-29 50 views
-2

我使用遊標來刪除一組表。表的數量大約是400.當計數達到105時,執行掛起。請找到以下腳本:如何在使用sqlserver中的遊標刪除大量表時清除死鎖?

DECLARE @TblName NVARCHAR(MAX); 
DECLARE TBL_Cur CURSOR 
FOR (select name from sysobjects 
     where name like 'xxx'); 
OPEN TBL_Cur; 
FETCH NEXT FROM TBL_Cur INTO @TblName 
      WHILE (@@FETCH_STATUS <> -1) 
     BEGIN 
      IF LEN(@TblName) >0 
      BEGIN 
       DECLARE @strsql nvarchar(max) 
      if ('Create_ts' IN (select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where table_name = @TblName)) 
      BEGIN 
        SET @strsql = 'Select count(*) from' + @TblName + ' where DATEDIFF(HOUR,create_ts,getdate())>1' 
        Begin try 
        BEGIN TRAN 
        EXEC sp_executesql @strsql 

        COMMIT TRAN 
        End Try 

        Begin Catch 

        End catch 
      END 
      END 
FETCH NEXT FROM TBL_Cur INTO @TblName 
END 
CLOSE TBL_Cur 
DEALLOCATE TBL_Cur 

在此先感謝您的幫助。

+1

呃,什麼?............... –

+2

我不知道你的意思,你的標題提到了我看不到的UPDATE,而你的問題機構提到了DELETE,我也沒有看到... –

+0

@Mitch wheat我不清楚你在問什麼? – charu

回答

0

我認爲查詢可以加快速度,如果不是執行字符串操作,而是一次執行它們,那麼您將不得不在光標上花費較少的時間。

我認爲你想要所有的表名與xxx +他們應該有一個'create_ts'列。修改了一下查詢。我的解決方案就像。

DECLARE @tbl Table(tableName nvarchar(MAX) null, stmt nvarchar(MAX) null) 

INSERT INTO @tbl(tablename, stmt) 
SELECT T.TABLE_NAME, 'SELECT count(*) FROM [' + T.TABLE_NAME + '] WHERE 
DATEDIFF(HOUR,create_ts,getdate())>1' 
FROM INFORMATION_SCHEMA.TABLES T 
INNER JOIN INFORMATION_SCHEMA.COLUMNS C ON T.TABLE_NAME = C.TABLE_NAME AND 
T.TABLE_SCHEMA= C.TABLE_SCHEMA 
WHERE T.TABLE_NAME like 'xxx' AND C.COLUMN_NAME = 'Create_ts' 

-- Open cursor and execute each row of @tbl 
-- also instead of executing each row in separate transaction, 
-- put the loop inside transaction and commit only once. 

DECLARE @tableToBeChecked nvarchar(MAX) 

IF NOT exists(SELECT object_name(P.object_id) as LockedTable FROM 
sys.dm_tran_locks AS L INNER JOIN sys.partitions AS P ON 
L.resource_associated_entity_id = p.hobt_id WHERE object_name(P.object_id) 
= @tableToBeChecked) 
BEGIN 
-- table is not locked and can be deleted safely. 
-- still no guarantee that by the time you arrive here the table 
-- would still be unlocked. 
END 
+0

您的劇本非常脆。但它又一次出現同樣的問題。 – charu

+0

我認爲它與列表中的某個表鎖定在一起。你有沒有想過如何跳過被鎖定的表格 – charu

+0

剛剛修改了代碼。現在檢查! –