将所有表的缺失行从一个数据库插入另一个数据库

时间:2017-02-28 02:35:30

标签: sql sql-server-2008 ssis

我有两个具有相同表格的数据库。每个表中的总行数在两个数据库之间不同。我必须将所有表的缺失行从一个数据库插入另一个数据库。

有没有办法一次性完成这一切?

我可以使用以下查询手动为每个表执行此操作:

将id视为唯一列:

insert into databasename.dbo.tablename
    select * 
    from datababasename2.dbo.tablename2
    where id not in (select id from databasename.dbo.tablename) 

我想对数据库中的所有表执行此操作。寻找动态的方法。

2 个答案:

答案 0 :(得分:0)

要传输1000行,只需删除并重新加载即可。这比尝试实现差异要简单得多。这是一些代码,其中大部分是错误处理。这不允许具有标识的表。如果是这种情况,请告诉我。

BEGIN TRY
BEGIN TRAN

DELETE TargetDB.dbo.TargetTable;

INSERT INTO TargetDB.dbo.TargetTable (column1,column2,column3)
SELECT column1,column2,column3 FROM SourceDB.dbo.SourceTable;

COMMIT TRAN
END TRY


BEGIN CATCH
  IF @@TRANCOUNT > 0
     ROLLBACK

  DECLARE @ErrMsg nvarchar(4000), @ErrSeverity int
  SELECT @ErrMsg = ERROR_MESSAGE(),
         @ErrSeverity = ERROR_SEVERITY()

  RAISERROR(@ErrMsg, @ErrSeverity, 1)
END CATCH

(提交/捕获模式从这里解除:http://www.4guysfromrolla.com/webtech/041906-1.shtml

答案 1 :(得分:0)

您可以使用包含SQL动态查询的存储过程来实现此目的:

CREATE PROCEDURE SyncDatabases
(
 @p_strSourceDatabase Varchar(50),
 @p_strDestinationDatabase Varchar(50),
 @p_Identity Bit --If your tables contains Identity columns
) AS 
BEGIN

DECLARE @strQuery VARCHAR(MAX)

CREATE TABLE #TblTemp(TABLE_SCHEMA VARCHAR(50), TABLE_NAME  VARCHAR(50), [COLUMNS] VARCHAR(MAX))

SET @strQuery = 'INSERT INTO #TblTemp (TABLE_SCHEMA , TABLE_NAME, COLUMNS)
                 SELECT DISTINCT T1.TABLE_SCHEMA,T1.TABLE_NAME, (SELECT ''['' + COLUMN_NAME + ''],'' FROM  [' + @p_strSourceDatabase + '].INFORMATION_SCHEMA.COLUMNS                            WHERE TABLE_NAME = T1.TABLE_NAME AND TABLE_SCHEMA = T1.TABLE_SCHEMA FOR XML PATH('''')) AS [COLUMNS]
                    FROM [' + @p_strSourceDatabase + '].INFORMATION_SCHEMA.COLUMNS AS T1 
                    INNER JOIN [' + @p_strDestinationDatabase + '].INFORMATION_SCHEMA.COLUMNS AS T2 
                    ON T1.TABLE_SCHEMA = T2.TABLE_SCHEMA
                    AND T1.TABLE_NAME  = T2.TABLE_NAME
                    AND T1.COLUMN_NAME = T2.COLUMN_NAME'


EXEC(@strQuery)

SET @strQuery = ''

SELECT @strQuery = @strQuery + CASE WHEN @p_Identity = 1 THEN 'SET IDENTITY_INSERT [' + @p_strDestinationDatabase + '].[' + T1.TABLE_SCHEMA + '].[' + T1.TABLE_NAME + '] ON ' ELSE '' END + ' INSERT INTO [' + @p_strDestinationDatabase + '].[' + T1.TABLE_SCHEMA + '].[' + T1.TABLE_NAME + '] (' + LEFT(T1.COLUMNS,LEN(T1.COLUMNS) - 1) + ')
        SELECT ' + LEFT(T1.COLUMNS,LEN(T1.COLUMNS) - 1) + ' FROM [' + @p_strSourceDatabase + '].[' + T1.TABLE_SCHEMA + '].[' + T1.TABLE_NAME + '] AS T1
        WHERE NOT EXISTS (SELECT 1 FROM [' + @p_strDestinationDatabase + '].[' + T1.TABLE_SCHEMA + '].[' + T1.TABLE_NAME + '] AS  T2 WHERE T1.ID =  T2.ID);
        '
        FROM #TblTemp AS T1

EXEC(@strQuery)  


DROP TABLE #TblTemp


END