Using the following two queries
Query 1:
DECLARE @ContentColumnNamesSRC NVARCHAR(4000) = NULL,
SELECT
@ContentColumnNamesSRC = COALESCE(@ContentColumnNamesSRC + ', ', '') + '[' + name + ']'
FROM
tempdb.sys.columns
WHERE
1 = 1
AND object_id = OBJECT_ID('tempdb..#tempTable')
AND column_id < 9 -- First 8 columns are ID data, which is what I am after
Query 2:
DECLARE @ContentColumnNamesDST NVARCHAR(4000) = NULL,
SELECT
@ContentColumnNamesDST = COALESCE(@ContentColumnNamesDST + ', ', '') + '[' + name + ']'
FROM
tempdb.sys.columns
WHERE
1 = 1
AND object_id = OBJECT_ID('Import.dbo.ContentTable')
AND column_id < 9 -- First 8 columns are ID data, which is what I am after
I can get the first 8 columns from each table into a variable.
What I would like to do is find a way to get the values out of the variable, such that I can match the column names.
They should be identical in each table, and I need it to be able to create a dynamic merge statement, such that the columnsnames from each variable
@ContentColumnNamesSRC
and
@ContentColumnNamesDST
line up, so I can use it in a merge statement.
The point of this is to be able to use it in a loop, and all i would have to do is change which tables it looks at and the merge statements would still work.
Ideally, id like to end up with something like the following:
SELECT @StageSQLCore = N'USE Staging;
BEGIN TRANSACTION
MERGE '+@StageTableCore+' AS DST
USING '+@ImportTableCore+' AS SRC
ON (SRC.[Key] = DST.[Key])
WHEN NOT MATCHED THEN
INSERT ('+@StageTableCoreColumns+')
VALUES (
'+@ImportTableCoreColumns+',GETDATE())
WHEN MATCHED
THEN UPDATE
SET
DST.'+@ContentColumnNamesDST[i]' = SRC.'+@ContentColumnNamesSRC[i] +'
,DST.'+@ContentColumnNamesDST[i]' = SRC.'+@ContentColumnNamesSRC[i] +'
,DST.'+@ContentColumnNamesDST[i]' = SRC.'+@ContentColumnNamesSRC[i] +'
,DST.'+@ContentColumnNamesDST[i]' = SRC.'+@ContentColumnNamesSRC[i] +'
,DST.[ETLDate] = GETDATE()
;
COMMIT'
EXEC (@StageSQLCore)
@ContentColumnNamesSRC), but with the dst.blah = src.blah, no?