2015-12-29 65 views
0

這裏是我用來針對sql server上的所有數據庫運行的腳本,但是當數據庫處於轉換狀態時腳本停止運行,所以我想要做的就是腳本需要跳過正在轉換的數據庫並繼續處理其餘的數據庫。任何幫助,將不勝感激。SQL Server在遊標定義的查詢中的異常處理

declare @name varchar(max) 

SET @starttime = GETDATE() 

Declare DB_cursor cursor for 
    SELECT Name 
    FROM sys.databases 
    WHERE name NOT IN ('master', 'model', 'msdb', 'tempdb') 
     AND is_read_only = 0 
     AND is_in_standby = 0 
     AND state = 0 

OPEN DB_cursor 

FETCH NEXT FROM DB_cursor INTO @name 

WHILE @@FETCH_STATUS = 0 
BEGIN 
    EXEC(' use [' + @name + '] IF EXISTS (select name from sys.objects where name=''@Tablename'') UPDATE STATISTICS [' + @SchemaName + '].[' + @TableName +'](['[email protected]+']) WITH FULLSCAN ') 

    FETCH NEXT FROM DB_cursor INTO @name 
END 

CLOSE DB_cursor 
DEALLOCATE DB_cursor 

回答

0

嘗試:

DECLARE @sql NVARCHAR(MAX) 
SET @sql = ' use [' + @name + '] IF EXISTS (select name from sys.objects where name=''@Tablename'') UPDATE STATISTICS [' + @SchemaName + '].[' + @TableName +'](['[email protected]+']) WITH FULLSCAN ') 

EXEC sp_executesql @sql = @sql