SqlServer更新視圖存儲過程函數腳本

--視圖、存儲過程、函數名稱
DECLARE @ NAME NVARCHAR(255);
--局部遊標
DECLARE @CUR CURSOR
--自動修改未上狀態爲曠課
SET @CUR= CURSOR SCROLL DYNAMIC FOR
SELECT NAME FROM DBO.SYSOBJECTS
     WHERE NAME NOT IN ( 'SYSCONSTRAINTS' , 'SYSSEGMENTS' )
         AND
         (
             OBJECTPROPERTY(ID, N 'IsView' ) = 1               --視圖
             OR OBJECTPROPERTY(ID,N 'IsProcedure' ) = 1        --存儲過程
             OR OBJECTPROPERTY(ID,N 'IsScalarFunction' ) = 1   --標量函數
             OR OBJECTPROPERTY(ID,N 'IsTableFunction' ) = 1    --標題函數
             OR OBJECTPROPERTY(ID,N 'IsInlineFunction' ) = 1   --內聯函數
         );
 
OPEN @CUR;
FETCH NEXT FROM @CUR INTO @ NAME
 
WHILE (@@FETCH_STATUS=0)
BEGIN
 
     DECLARE @OldText NVARCHAR( MAX );
     DECLARE @NewText NVARCHAR( MAX );
 
     --讀取建立腳本,當腳本超長時分紅多條記錄時合併
     SELECT @OldText=@OldText + CHAR (10) + CHAR (13) + RTRIM(TEXT) FROM SYSCOMMENTS WHERE ID = OBJECT_ID(@ NAME );
 
     --將建立腳本替換爲更新腳本
     SET @NewText= REPLACE (@OldText,N 'CREATE VIEW' ,N 'ALTER VIEW' );
     SET @NewText= REPLACE (@NewText,N 'CREATE PROCEDURE' ,N 'ALTER PROCEDURE' );
     SET @NewText= REPLACE (@NewText,N 'CREATE FUNCTION' ,N 'ALTER FUNCTION' );
     
     BEGIN TRY
         EXEC (@NewText);
     END TRY
     BEGIN CATCH
         PRINT N '---------------------------------------------------------------------------' ;
         PRINT @ NAME + N ' : ' + ERROR_MESSAGE();
         --PRINT @OldText;
         PRINT N '---------------------------------------------------------------------------' ;
     END CATCH
 
     FETCH NEXT FROM @CUR INTO @ NAME
 
END
 
CLOSE @CUR;
DEALLOCATE @CUR;
相關文章
相關標籤/搜索