sql server - SQL Update Two Identical Tables -
I have two identical tables that need to be updated on a daily basis. Both tables have the same structure. If they have 100+ columns, is there a way to update all the columns based on tablebine without writing a (set column name = '') update statement for each column in SQL? Both tables have the same column names, so I thought there might be a clever way of doing this.
This is a little hack but it can be done.
I have created two identical tables with every 2 records. (Table_1 and Table_2)
Table_2 SQL: Table_2 Edit is a bit more complex, but it does not include primary key columns:
Table_1
DECLARE @ LEFTTABLE VARCHAR (MAX) = 'Table_1'; DECLARE @RightTable VARCHAR (MAX) = 'Table_2'; DECLARE @UpdateStatementVARCHAR (MAX); SELECT @UpdateStatement = COALESCE (@UpdateStatement + ',', '') + 't2.' + COLUMN_NAME + '= 1.' INFORMATION_SCHEMA.COLUMNS from COLUMN_NAME, where TABLE_NAME = @ LiftTable and COLUMN_NAME & lt; & Gt; 'Id' SET @UpdateStatement = 'UPDATE T2 SET' + @UpdateStatement + '' + 'FROM' + @righttable + 't2 join' + left-tile + '' + 1t1 on t.2id = t1 .Id '; EXEC (@UpdateStatement) - The actual execution query is: - Update T2 SET t2.Description = t1. Definition, - T2. Extra = T1. Extra - Include table 2 T2 Table 1 T1 on T.ID = Add T1 ID
Result: Table_1 < / Strong>
DECLARE @ LEFTTABLE VARCHAR (MAX) = 'Table_1'; DECLARE @RightTable VARCHAR (MAX) = 'Table_2'; DECLARE @UpdateStatementVARCHAR (MAX); Enter the ID as the column name (SE.C. Idx.index_id = ic.index_id and idx.object_id = ic.object_id and idx.is_primary_key = 1 on sys.index_columns ic t.object_id = idx.object_id and c. Column_id = idx.column_id WHERE t.name = @ lefttable and idx.index_name is IS tap) SELECT @UpdateStatement = COALESCE (@UpdateStatement + ',', '') + 't2.' + COLUMN_NAME + '= 1.' + COLUMN_NAME + CHAR (10) SET @UpdateStatement = 'UPDATE T2 SET' + @UpdateStatement + CHAR (10) + 'FROM' + @RightTable + 'T2 JOIN' + @LiftTable + CHAR (10) + 'T1 On T2.ID = t1.ID '; EXEC (@UpdateStatement)
Comments
Post a Comment