資料庫資料複製

2021-04-02 10:28:14 字數 2774 閱讀 2192

/*--資料庫資料複製

將乙個資料庫中的資料複製到另乙個資料庫

如果某列在目標資料庫中為標識列,將不會被複製

適用範圍:資料庫結構發生了變化,想將舊資料庫進行公升級

這樣就可以根據新的資料庫結構建立乙個空庫,然後

將舊資料庫的所有資料複製到新庫中

--*/

/*--呼叫示例

exec p_copydb '源資料庫','目標資料庫'

exec p_copydb 'acc_五醫','acc_演示資料8'

--*/

if exists (select * from dbo.sysobjects where id = object_id(n'[dbo].[p_copydb]') and objectproperty(id, n'isprocedure') = 1)

drop procedure [dbo].[p_copydb]

gocreate proc p_copydb

@o_dbname sysname,  --要複製資料的資料庫--源資料庫

@n_dbname sysname,  --接收資料的資料庫--目標資料庫

@cleardb bit=0   --清空目標資料庫

asdeclare @sql nvarchar(4000)

--禁用約束,防止複製時的資料衝突

set @sql='declare #tbc cursor for select name,tbname=object_name(parent_obj)

from '+@n_dbname+'..sysobjects where xtype in(''c'',''f'')'

exec(@sql)

declare @name sysname,@tbname sysname

open #tbc

fetch next from #tbc into @name,@tbname

while @@fetch_status=0

begin

set @sql='alter table '+@n_dbname+'..['+@tbname+'] nocheck constraint ['+@name+']'

exec(@sql)

fetch next from #tbc into @name,@tbname

endclose #tbc

--複製資料

declare @sql1 varchar(8000)

set @sql='declare #tb cursor for select a.name from '

+@o_dbname+'..sysobjects a inner join '

+@n_dbname+'..sysobjects b on a.name=b.name

where a.xtype=''u'' and b.xtype=''u'''

exec(@sql)

open #tb

fetch next from #tb into @tbname

while @@fetch_status=0

begin

select @sql1=''

,@sql='select @sql1=@sql1+'',[''+a.name+'']'' from(

select name from '+@o_dbname+'..syscolumns where id in

(select id from '+@o_dbname+'..sysobjects where name='''+@tbname+''')

) a inner join (

select name from '+@n_dbname+'..syscolumns where status<>0x80 and id in

(select id from '+@n_dbname+'..sysobjects where name='''+@tbname+''')

) b on a.name=b.name'

exec sp_executesql @sql,n'@sql1 nvarchar(4000) out',@sql1 out

select @sql1=substring(@sql1,2,8000)

exec('insert into '+@n_dbname+'..['+@tbname+']('+@sql1

+') select '+@sql1+' from '+@o_dbname+'..['+@tbname+']')

if @@error<>0

print('insert into '+@n_dbname+'..['+@tbname+']('+@sql1

+') select '+@sql1+' from '+@o_dbname+'..['+@tbname+']')

fetch next from #tb into @tbname

endclose #tb

deallocate #tb

--資料複製完成後啟用約束

open #tbc

fetch next from #tbc into @name,@tbname

while @@fetch_status=0

begin

set @sql='alter table '+@n_dbname+'..['+@tbname+'] check constraint ['+@name+']'

exec(@sql)

fetch next from #tbc into @name,@tbname

endclose #tbc

deallocate #tbc

go

複製資料庫

複製資料庫 sql200企業管理器 右鍵要複製的資料庫a 所有任務 匯出資料 目標資料庫,選擇資料庫b 然後選擇 在sql server資料庫之間複製資料和物件 勾選 建立目的物件 包含擴充套件屬性 最後完成.或者查詢分析器執行下面的語句建立乙個儲存過程,然後再執行呼叫示例中的呼叫方法實現資料庫複製...

資料庫複製

if exists select from dbo.sysobjects where id object id n dbo p copydb and objectproperty id,n isprocedure 1 drop procedure dbo p copydb go 資料庫資料複製 將乙...

資料庫複製

if exists select from dbo.sysobjects where id object id n dbo p copydb and objectproperty id,n isprocedure 1 drop procedure dbo p copydb go 資料庫資料複製 將乙...