I'm trying to create a dynamic merge query inside a stored procedure where target is a history table and source is a temporary table - SQL Server

538 views Asked by At
SET @COLUMNNAMES_HIST= ( SELECT STRING_AGG( COLUMN_NAME, ' ,') COLUMN_NAMES FROM INFORMATION_SCHEMA.COLUMNS WHERE UPPER(TABLE_SCHEMA) = '@SCHEMANAME' AND UPPER(TABLE_NAME) = '@TABLE_HIST';                

SET @MERGESQL = 'MERGE ' +  @TABLE_HIST + ' USING #FINAL_TEMP_CPY SRC
ON (TGT.@PRIMARYKEY = SRC.@PRIMARYKEY AND TGT.UPDATE_TIMESTAMP = SRC.UPDATE_TIMESTAMP)
WHEN NOT MATCHED BY TARGET
            THEN INSERT
            (
                @COLUMNNAMES_HIST -- Column list
            ) 
        
            (
                SELECT *, GETTIMESTAMP(),  GETTIMESTAMP() FROM FINAL_TEMP_CPY;
            )'

I am fetching all the columns from TABLE_HIST first into a variable and that I am using in INSERT statement. Is that alright? And then in values I am fetching all values from source table and getting timestamp at the same time for other two columns in the TABLE_HIST. Do you think this will work?

0

There are 0 answers