====== ======
===== Explanation of SQL =====
This SQL query creates a stored procedure that can be used to copy values from one table into another __even if the two databases are not identical__. This is helpful is the field layout of the source and destination table are different, for example. Or if not all of the fields in one table are found in the other.
Notes:
* The intersection of all fields found in the two tables are moved. (i.e., The field must be found in both tables.)
* It will NOT replace any records already found in the destination table (based on the ID)
* You can specify a custom WHERE clause that will be used to filter the source table and only move certain records.
==Sample Usage==
exec Insert_Into_Table 'BackupData', 'TempPC', 'StoreData', 'PostalCodeTaxClass'
exec Insert_Into_Table 'BackupData', 'PostalCodeTaxClass', 'StoreData', 'PostalCodeTaxClass', 'ModifiedDate > ''12/1/2009'' '
===== Risk of Data Corruption if Run Improperly =====
**High**. You are updating the data in the Destination Database. Do not run this except under the direction of a Cyrious Technical Support staff member. Doing otherwise may result in lost or contaminated data. All data modifications done through direct SQL **are permanent and non-reversable**.
===== SQL =====
--------------------------------------------------------------------------------------
-- Section: Insert_Into_Table Stored Procedure
--
-- This section defines a stored procedure that inserts the NEW data in working table
-- into the destination database.
--
-- Other Notes:
-- * Only new data is inserted.
-- * A custom field list is generated for the working and destination table so that
-- the order of the fields does NOT need to match.
--------------------------------------------------------------------------------------
CREATE PROCEDURE Insert_Into_Table
@SourceDatabase varchar(255),
@SourceTableName varchar(50),
@DestDatabase varchar(255),
@DestTableName varchar(50),
@CustomWhereClause varchar(max) = ''
AS
BEGIN
SET @DestDatabase = @DestDatabase+'.dbo.';
SET @SourceDatabase = @SourceDatabase+'.dbo.';
DECLARE @S VarChar(max);
-- Create a list of columns common in both the source and destination tables
-- Sorted in the order found in the destination table
Declare @ColumnNames varchar(max);
SET @ColumnNames = NULL
BEGIN TRY
CREATE TABLE #ColumnNames (ColumnName Varchar(255), ColumnIndex int);
SET @S =
'INSERT INTO #ColumnNames '+
'Select * FROM '+
'( '+
' SELECT A.[name] AS ColumnName, ' +
' A.[colid] as ColumnIndex ' +
' FROM '+@DestDatabase+'syscolumns A ' +
' join '+@SourceDatabase+'syscolumns B ' +
' ON A.[name] = B.[name] ' +
' WHERE ' +
' A.id in ' +
' (SELECT id FROM '+@DestDatabase+'sysobjects ' +
' WHERE type = ''U'' ' +
' AND [NAME] = '''+@DestTableName+''') ' +
' and B.id in ' +
' (SELECT id FROM '+@SourceDatabase+'sysobjects ' +
' WHERE type = ''U'' ' +
' AND [NAME] = '''+@SourceTableName+''') ' +
') Temp ' +
'ORDER BY ColumnIndex ';
Execute(@S);
SELECT @ColumnNames = COALESCE(@ColumnNames + ',', '') + '[' + ColumnName + '] '
FROM #ColumnNames
ORDER BY ColumnIndex
-- Insert the Table Contents
SET @S=
'INSERT INTO ' + @DestDatabase+@DestTableName + ' ('+@ColumnNames+' ) ' +
'SELECT '+@ColumnNames+' FROM '+ @SourceDatabase+@SourceTableName + ' ' +
'WHERE ID > 0 AND ID NOT IN (SELECT ID FROM '+@DestDatabase+@DestTableName+') ';
IF (Coalesce(@CustomWhereClause, '') '')
SET @S = @S + ' AND '+@CustomWhereClause
-- When there is text larger than 8K, SQL will terminate with an error
-- This disabled that (not desired, but the alternate is less desireable)
--
SET ANSI_WARNINGS OFF
-- Print @S
-- Print ''
Print 'Inserting Records into '+@DestDatabase+@DestTableName
EXECUTE(@S);
SET ANSI_WARNINGS ON
-- Clean up after ourselves
DROP TABLE #ColumnNames;
END TRY
BEGIN CATCH
PRINT '-------------------------';
PRINT 'Oops! An Error Occurred.';
PRINT
' Message: '+ Coalesce(ERROR_MESSAGE(),'NULL');
PRINT
' Error Number: '+ Coalesce(Cast(ERROR_NUMBER() AS VarChar(20)),'NULL') +
' Severity: '+ Coalesce(Cast(ERROR_SEVERITY() AS VarChar(20)),'NULL') +
' State: '+ Coalesce(Cast(ERROR_STATE() AS VarChar(20)),'NULL') +
' Procedure: '+ Coalesce(Cast(ERROR_PROCEDURE() AS VarChar(50)),'NULL') +
' Line: '+ Coalesce(Cast(ERROR_LINE() AS VarChar(20)),'NULL');
PRINT ' Column Names: '+coalesce(@ColumnNames, 'NULL');
PRINT ' Last SQL Run: '+coalesce(@S, 'NULL');
PRINT '-------------------------';
END CATCH
END;
--------------------------------------------------------------------------------------
===== Version Information =====
* Entered : 12/2009
* Version : All