批量导出存储过程

今天遇到了一个问题,需要把原数据库的一些数据导入到新数据库中,其中包括700多条存储过程。

开始通过sql语句查询出所有的存储过程,然后再创建,发现创建存储过程时不能同时创建多个。

select sm.object_id, object_name(sm.object_id) as object_name, o.type, o.type_desc, sm.definition
    from sys.sql_modules sm inner join sys.objects o on sm.object_id = o.object_id
        where o.type = 'P' and o.name not like '%diagram%' order by o.name;

如果想要同时创建多个存储过程,需要在每个存储过程之间加入"go",然后再执行。

后来通过高人指点,用下面的sql语句备份原数据库的存储过程,再在新数据库执行即可。

create table #sql_modules(id int identity(1,1), definition nvarchar(max))

insert into #sql_modules
select sm.definition
        from sys.sql_modules sm inner join sys.objects o on sm.object_id = o.object_id
            where o.type = 'P' and o.name not like '%diagram%' order by o.name;

declare @counter    int = 1
declare @max_count    int = (select max(id) from #sql_modules);

declare @sql_modules table(definition nvarchar(max))

while @counter <= @max_count
begin
    insert into @sql_modules
    
    select definition from #sql_modules where id = @counter
    union all
    select 'go'
        
    set @counter = @counter + 1;
end

select * from @sql_modules;
drop table #sql_modules;

 

posted @ 2013-07-16 22:04  MorrisS  阅读(1008)  评论(0编辑  收藏  举报