mssql批量更新程序和功能

时间:2014-12-04 09:33:53

标签: sql-server tsql

我们有一些包含大量视图,功能和程序的数据库。 我们将更新其中一些。因此我写了这个脚本。 我的问题是,这是一种常见的方式,并且是正确的方式吗?

任何建议都将受到赞赏。

--  update procedures and functions
USE mydb
GO
DECLARE @ticker nvarchar(255)
DECLARE @definition nvarchar(max)
DECLARE @newdefinition nvarchar(max)
DECLARE crsVorgang SCROLL CURSOR FOR
    SELECT ROUTINE_NAME,ROUTINE_DEFINITION FROM INFORMATION_SCHEMA.ROUTINES
    WHERE ROUTINE_CATALOG = 'mydb' and ROUTINE_DEFINITION like '%something%' 
    ORDER BY ROUTINE_NAME 

        OPEN crsVorgang
        FETCH FIRST FROM crsVorgang INTO @ticker, @definition

        WHILE (@@FETCH_STATUS <> -1)
        BEGIN

            set @newdefinition = REPLACE(@definition,'sometext', 'newtext')

            --print @newdefinition
            update INFORMATION_SCHEMA.ROUTINES
            set ROUTINE_DEFINITION = @newdefinition
            where ROUTINE_NAME = @ticker

        FETCH NEXT FROM crsVorgang INTO @ticker, @definition
        END
    CLOSE crsVorgang
    DEALLOCATE crsVorgang
GO

1 个答案:

答案 0 :(得分:0)

答案是,更新INFORMATION_SCHEMA.ROUTINES是不可能的,因为不允许这样做。

正确的方式(对我而言)来自许多程序和函数的可重现批量更新现在是一个drop和create,所以我已经将我的脚本修改为以下内容:

USE [mydb]
GO
DECLARE @ticker nvarchar(255)
DECLARE @definition nvarchar(max)
DECLARE @routinetype nvarchar(255)
DECLARE @newdefinition nvarchar(max)
DECLARE @dropdefinition nvarchar(max)
DECLARE crsVorgang SCROLL CURSOR FOR
    SELECT ROUTINE_NAME,ROUTINE_DEFINITION, ROUTINE_TYPE FROM INFORMATION_SCHEMA.ROUTINES
    WHERE ROUTINE_CATALOG = 'mydb' and ROUTINE_DEFINITION like '%something%' 
    ORDER BY ROUTINE_NAME 

        OPEN crsVorgang
        FETCH FIRST FROM crsVorgang INTO @ticker, @definition, @routinetype

        WHILE (@@FETCH_STATUS <> -1)
        BEGIN

            set @dropdefinition = 'DROP '+ @routinetype +' [dbo].'+@ticker
            set @newdefinition = REPLACE(@definition,'sometext', 'newtext')

            exec (@dropdefinition)
            exec (@newdefinition)

        FETCH NEXT FROM crsVorgang INTO @ticker, @definition, @routinetype
        END
    CLOSE crsVorgang
    DEALLOCATE crsVorgang
GO

感谢您花费的时间