下面我们开始介绍用存储过程实现SQL Server数据库的同步方法,首先说明,我们使用的存储过程是需要运行在服务器上的,假如换库,不需要修改任何东西。接下来我们就逐步演示这一过程:
建立存储所有表名的表:
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].p_bakup_tatle_all') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].p_bakup_tatle_all GO create proc p_bakup_tatle_all as if exists (select * from dbo.sysobjects where id = object_id(N'table_all ') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table table_all CREATE TABLE [dbo].[Table_all]( [id] [int] IDENTITY(1,1) NOT NULL, [name] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL, CONSTRAINT [PK_Table_all] PRIMARY KEY CLUSTERED ( [id] ASC )WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY] ) ON [PRIMARY]
将所有表名存放在表table_all中:
insert into table_all(name) select name from sysobjects where xtype='U' GO
备份服务器上的存储过程,若换库,需要修改InfoCenter两处,还有连接服务的地址。
创建数据同步的存储过程:
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].p_bakup_tatle_all') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].p_bakup_tatle_all GO create proc p_bakup_tatle_all as
创建链接服务器:
exec sp_addlinkedserver 'ITSV ', ' ', 'SQLOLEDB ', '61.135.203.103' exec sp_addlinkedsrvlogin 'ITSV ', 'false ',null, 'sa', 'comsky103@2011.com'
查询示例 select * from ITSV.test.dbo.[users]。
导入将服务器上的表以及数据保存在本地:
if exists (select * from dbo.sysobjects where id = object_id(N'table_all ') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table table_all select * into table_all from ITSV.InfoCenter.dbo.table_all DECLARE @Name varchar(50),@count int,@i int set @i=1 select @countcount=count(*) from table_all while @i<=@count begin select @Name=name from table_all where id=@i if exists(select name from sysobjects where name=''+@name+'' and type='u') exec('drop table ['+@Name+']') exec('select * into ['+@Name+'] from ITSV.InfoCenter.dbo.['+@Name+']' ) PRINT @Name set @i=@i+1 PRINT @i
以后不再使用时删除链接服务器:
exec sp_dropserver 'ITSV ', 'droplogins' go
以上就是用存储过程实现SQL Server数据库同步的全部过程,本文就介绍到这里,谢谢大家的支持!