本文给大家分享一个远程更新目标库数据的存储过程,适用于更新列名一致,主键为Int类型,可远程链接的数据库。
USE [Table]--切换到源表,就是数据最新的那个表GO/****** Object: StoredProcedure [dbo].[proc_DataUpdate] Script Date: 2018/5/4 15:08:56 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGO-- =============================================-- Author: <Grom>-- Create date: <2018-05-04>-- Description: <分批更新远程数据,仅支持主键为int表>-- =============================================CREATE PROCEDURE [dbo].[proc_DataUpdate]@TargetInstance nvarchar(max),@TargetDBName nvarchar(max),@TargetUID nvarchar(max),@TargetPWD nvarchar(max),@LocalDBName nvarchar(max),@PK_ID nvarchar(max),--主键列(必须为数字)@Column nvarchar(max),--更新列名集合@ExecSize int--每次执行数量ASdeclare @sql nvarchar(max),@NumMax int=0,@NumMin int=0,@MaxID int BEGIN-- SET NOCOUNT ON added to prevent extra result sets from-- interfering with SELECT statements.-- SET NOCOUNT ON;--打开注释可不显示执行过程,提高速度begin try --取最大值 set @sql = 'select @MaxID=MAX('+@PK_ID+') from '+@LocalDBName; exec sp_executesql @sql,N'@MaxID int out',@MaxID out --循环 while(@NumMax<@MaxID) begin if exists (select * from tempdb.dbo.sysobjects where id = object_id(N'tempdb..##tmp_table') and type='U') drop table ##tmp_table; SET @sql = 'select top '+cast(@ExecSize as nvarchar(1000))+' '+ @Column +' into ##tmp_table from '+@LocalDBName+' where '+@PK_ID+'>'+cast(@NumMax as nvarchar(150)); exec sp_executesql @sql; --记录执行最大值 SET @SQL='select @NumMax=MAX('+@PK_ID+') from ##tmp_table'; exec sp_executesql @sql,N'@NumMax int out',@NumMax out; --记录执行最小值 SET @SQL='select @NumMin=MIN('+@PK_ID+') from ##tmp_table'; exec sp_executesql @sql,N'@NumMin int out',@NumMin out; SET @sql='delete openrowset(''SQLOLEDB'','''+@TargetInstance+''';'''+@TargetUID+''';'''+@TargetPWD+''',['+@TargetDBName+'].[dbo].['+@LocalDBName+']) where '+@PK_ID+' between '+cast(@NumMin as nvarchar(200))+' and '+cast(@NumMax as nvarchar(200)); exec sp_executesql @sql; SET @sql='insert into openrowset(''SQLOLEDB'','''+@TargetInstance+''';'''+@TargetUID+''';'''+@TargetPWD+''',['+@TargetDBName+'].[dbo].['+@LocalDBName+']) ('+@Column+') select '+ @Column +' from ##tmp_table' exec sp_executesql @sql; end --删除多余数据 SET @sql='delete openrowset(''SQLOLEDB'','''+@TargetInstance+''';'''+@TargetUID+''';'''+@TargetPWD+''',['+@TargetDBName+'].[dbo].['+@LocalDBName+']) where '+@PK_ID+' >'+cast(@NumMax as nvarchar(200)); drop table ##tmp_table; print 'Success';end trybegin catch select Error_number() as ErrorNumber, --错误代码 Error_severity() as ErrorSeverity, --错误严重级别,级别小于10 try catch 捕获不到 Error_state() as ErrorState , --错误状态码 Error_Procedure() as ErrorProcedure , --出现错误的存储过程或触发器的名称。 Error_line() as ErrorLine, --发生错误的行号 Error_message() as ErrorMessage --错误的具体信息 drop table ##tmp_table;end catchEND
新闻热点
疑难解答