批量替换存储过程内容脚本sp_SqlReplace

开始

在数据库开发过程中,如果某一个表字段名被重命名。那么在使用到该字段的存储过程,对应的表字段名也要修改。

当存在多个存储都有使用该表字段,需要逐个去修改替换,是一件比较繁琐的事情,我们需要一个能实现批量替换的方法。

 

这里我写了一个批量替换存储过程内容的脚本:

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
复制代码

 

 

 调用方法

 

 

posted @   ok_008  阅读(1083)  评论(1编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
给我写信
点击右上角即可分享
微信分享提示