格式化语句是借鉴了网上另一位大佬的语句,只是将他写的存储过程变成了函数以便获取返回值。
首先创建一个格式化函数:
create function [dbo].[my_helptext](
@name varchar(255)
)
returns @source table(
source varchar(max)
)
as
begin
declare @object_id int,
@sourcecode varchar(max),
@line varchar(max),
@end int,
@rn varchar(2),
@tab varchar(1)
set @rn = char(13)+char(10)
set @tab = char(9)
select @sourcecode = definition from sys.sql_modules where object_id=object_id(@name)
while(charindex(@rn,@sourcecode)!=0)
begin
set @end=charindex(@rn,@sourcecode)
set @line = replace(substring(@sourcecode,1,@end-1),@tab,@tab+@tab)
if(charindex('create',@line)<>0 and (charindex('proc',@line)<>0 or charindex('view',@line)<>0 or charindex('function',@line)<>0 or charindex('trigger',@line)<>0))
begin
set @line = replace(@line,'create','alter')
end
insert into @source(source) values(@line)
set @end = @end + 1
set @sourcecode = substring(@sourcecode,@end,len(@sourcecode))
end
insert into @source(source) values(@sourcecode)
return
end
然后利用游标遍历所有存储过程名称,并将内容插入临时表,最后查询出来,然后就可以复制粘贴到EXCEL中
declare @name varchar(200) ;
declare cur_name cursor scroll
for
select name from sys.objects where type='P' ;
open cur_name ;
fetch first from cur_name into @name ;
while @@FETCH_STATUS = 0
begin
set @name = ''+@name+'' ;
insert into #aa
select * from my_helptext(@name) a ;
insert into #aa values('------------------------这是分割线---------------------------')
fetch next from cur_name into @name ;
end ;
select * from #aa ;
#aa这个临时表我偷懒了 需要先创建一个,如果直接用 select * into #aa from my_helptext(@name) a , 则在查找第二个存储过程并执行插入动作时就会报错,系统中已经存在临时表#aa ,我就懒得去做判断了,直接在运行一次报错后,清空了临时表,然后改用 insert into #aa select * from my_helptext(@name) a ;
另外,复制到EXCEL中,格式上还是有些小问题,本来应该在第一列中的内容,分布到了第三列,可能是大佬的格式化语句上需要优化,我就没去仔细研究了,导出的结果并不影响观看。