批量替換存儲過程內容腳本sp_SqlReplace

開始

在數據庫開發過程當中,若是某一個表字段名被重命名。那麼在使用到該字段的存儲過程,對應的表字段名也要修改。sql

當存在多個存儲都有使用該表字段,須要逐個去修改替換,是一件比較繁瑣的事情,咱們須要一個能實現批量替換的方法。數據庫

 

這裏我寫了一個批量替換存儲過程內容的腳本:ide

sp_SqlReplace

Use master
Go
if object_ID('[sp_SqlReplace]') is not null
    Drop Procedure sp_SqlReplace
Go
create proc sp_SqlReplace
(
    @OriginalText nvarchar(max),
    @CurrentText nvarchar(max)
)
as  
Set Nocount On

Declare @Count int=0,@i int=1,@sql1 nvarchar(max),@sql2 nvarchar(max),@objectname sysname;
Declare @tblTmp Table(ID int identity primary key,objectID int,objectName sysname)

Insert Into @tblTmp(objectID,objectName) Select distinct  id,object_name(id) From sys.syscomments Where text like '%'+@OriginalText+'%'
Set @Count=@@ROWCOUNT

If @Count=0 Return 

Begin Try
    Begin Transaction
    While @i<=@Count
    Begin
        Select @sql1='if object_id('''+quotename(objectName)+''') Is Not null Drop '+case  when object_id(objectName,N'P') is not null then 'Procedure ' when Coalesce(object_id(objectName,N'FN'),object_id(objectName,N'IF'),object_id(objectName,N'TF')) is not null then 'Function ' when object_id(objectName,N'TR') is not null then 'Trigger ' else 'View 'end+Quotename(objectName) ,
                @sql2=Replace(object_definition(objectID),@OriginalText,@CurrentText),
                @objectname=objectName
            From @tblTmp 
            Where ID=@i
            
        Exec (@sql1)    
        Print @objectname
        
        Exec (@sql2)
        
        Set @i+=1
    End    
    Commit Transaction
    Select N'影響到對象有:' As [信息提示]
    Select 'Exec sp_sql '+objectName As [對象名稱],case  when object_id(objectName,N'P') is not null then 'Procedure ' when Coalesce(object_id(objectName,N'FN'),object_id(objectName,N'IF'),object_id(objectName,N'TF')) is not null then 'Function ' when object_id(objectName,N'TR') is not null then 'Trigger ' else 'View 'end As [類型] From @tblTmp
End Try
Begin Catch    
    Rollback transaction
    throw
End Catch
Go

 

 

 調用方法

 

相關文章
相關標籤/搜索