您的位置:首页 > 数据库

将一个数据库中的存储过程,复制到另一数据库

2005-11-24 17:13 453 查看
1use master
2go
3
4if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_copyProce]') and
5
6OBJECTPROPERTY(id, N'IsProcedure') = 1)
7drop procedure [dbo].[sp_copyProce]
8GO
9
10
17
22create proc sp_copyProce
23@s_dbname sysname, --要复制存储过程的源数据库名
24@d_dbname sysname --目标数据库名
25as
26set nocount on
27if db_id(@s_dbname) is null
28begin
29 raiserror('数据库"%s"不存在',1,16,@s_dbname)
30 return
31end
32if db_id(@d_dbname) is null
33begin
34 raiserror('数据库"%s"不存在',1,16,@d_dbname)
35 return
36end
37select @s_dbname='['+replace(@s_dbname,']',']]')+']'
38 ,@d_dbname='['+replace(@d_dbname,']',']]')+']'
39
40--复制存储过程信息到临时表
41create table #sys_syscomments_bak(name sysname,xtype char(2),number smallint,colid
42
43smallint,status smallint,ctext varbinary(8000))
44exec('
45insert #sys_syscomments_bak
46 (name,xtype,number,colid,status,ctext)
47select o.name,o.xtype,c.number,c.colid,c.status,c.ctext
48from '+@s_dbname+'.dbo.syscomments c,'+@s_dbname+'.dbo.sysobjects o
49where c.id=o.id
50 and o.status>=0
51 and o.xtype=''P''
52 and not exists(
53 select * from '+@d_dbname+'.dbo.sysobjects where name=o.name)
54')
55
56--创建存储过程
57declare tb cursor local for
58select 'use '+@d_dbname+' exec(''create proc dbo.['+replace(name,N']',N']]')+'] as --'')
59
60exec sp_recompile ['+replace(name,N']',N']]')+']'
61from #sys_syscomments_bak
62declare @s nvarchar(4000)
63open tb
64fetch tb into @s
65while @@fetch_status=0
66begin
67 exec(@s)
68 fetch tb into @s
69end
70close tb
71deallocate tb
72
73--复制存储过程结构
74exec sp_configure 'allow updates',1 reconfigure with override
75begin tran
76 exec('
77 delete c
78 from '+@d_dbname+'.dbo.syscomments c,'+@d_dbname+'.dbo.sysobjects
79
80o,#sys_syscomments_bak ob
81 where c.id=o.id and o.name=ob.name and o.xtype=ob.xtype
82 insert '+@d_dbname+'.dbo.syscomments([id],[number],[colid],[status],[ctext])
83 select o.[id],ob.[number],ob.[colid],ob.[status],ob.[ctext]
84 from '+@d_dbname+'.dbo.sysobjects o,#sys_syscomments_bak ob
85 where o.name=ob.name and o.xtype=ob.xtype')
86commit tran
87exec sp_configure 'allow updates',0 reconfigure with override
88go
89
90
91--使用测试
92create database a
93go
94use a
95go
96create proc p_test1
97as
98select 'test1'
99go
100
101
102create proc p_test2
103as
104select 'test2'
105go
106
107create database b
108go
109
110exec master.dbo.sp_copyProce 'a','b'
111go
112select * from b.dbo.sysobjects where xtype='P'
113
114exec b.dbo.p_test1
115exec b.dbo.p_test2
116go
117
118use master
119go
120
121drop database a,b
122drop proc sp_copyProce
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: