分享

SQL Server使用存储过程+事务+游标跨库将一个表中的数据导出到另一服务器的两个数据库表中

 tjmarm 2013-10-29

根据工作需要有时需要迁移大量的数据,于是按自己的想法做了一个数据迁移的存储过程,欢迎大家提出更好的建议,完整的存储过程如下:

create procedure DataMove --创建存储过程

--ALTER procedure DataMove --修改存储过程

as

BEGIN

declare @MaxID int--插入到文章表后的新ID

declare @Count int--统计迁移数据的条数

set @Count=0

--如存在跨库链接服务器,则删除

if exists(select * from master..sysservers where srvname= 'srv_lnk')

exec sp_dropserver  'srv_lnk', 'droplogins'

--建立跨库链接服务器

exec sp_addlinkedserver  'srv_lnk','','SQLOLEDB','172.16.14.55'--最后一个参数为数据库服务器地址

exec sp_addlinkedsrvlogin 'srv_lnk','false',null,'sa','sa'--最后两个个参数为数据库服务器的登录用户名和密码

 

declare mycursor cursor for 

select id from srv_lnk.kxyjdb.dbo.PageContent where 主类=5

declare @id int

open mycursor

 

fetch next from mycursor into @id

while @@fetch_status = 0

begin

if not exists(select * from ZWY.dbo.Article a where a.Title=(select 标题 from srv_lnk.kxyjdb.dbo.PageContent b where id=@id))

BEGIN

begin tran mytran --开始执行事务

--向文章表导入数据

INSERT ZWY.dbo.Article(CategoryID,Title, [Content],UserID, Username,IsCheck,IsLock) 

SELECT 46,标题,内容,2,'admin',1,0

FROM srv_lnk.kxyjdb.dbo.PageContent

WHERE id=@id

set @MaxID=@@identity --得到最新插入记录的ID

--print @MaxID

 

--向文章字段扩展表导入数据

INSERT ZWY.dbo.ExtendTable_ArticleType_9(ArticleID, XueKe, KanMing,JuanQi, CaiJiWangZhi, CaiJiShiJian,FuJian) 

SELECT @MaxID,学科,发者,发时,采址,采时, '/attachment/'+附件

FROM srv_lnk.kxyjdb.dbo.PageContent

WHERE id=@id

 

set @Count=@Count+1

 

if @@error<>0 --判断如果两条语句有任何一条出现错误

begin

rollback tran mytran--开始执行事务的回滚,恢复的转账开始之前状态

end

else  --如何两条都执行成功

begin

commit tran mytran--执行这个事务的操作

end

END--END if

 

fetch next from mycursor into @id

end--end while

close mycursor

DEALLOCATE mycursor

 

exec sp_dropserver  'srv_lnk', 'droplogins'--删除跨库链接服务器

 

 

return @Count --返回导入记录条数

END

--测试存储过程

--declare @return_status int

--exec @return_status= DataMove

--print @return_status

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多