I have a table (tblStagingHeader) containing the below two columns and example data. It is a record of SQL table names that have been created as part of an SSIS\ETL load.
StageTable Inserted
-------------------------
tblStage1 0
tblStage2 0
tblStage3 0
Using the below SQL task, I dynamically insert data from the staging tables (e.g. tblStage1 etc) into real tables.
My question is - after each successful insert, how do I loop through the tblStagingHeader and change the 'Inserted' field from a '0' to a '1' for each corresponding StageTable?
--NOTE: the actual EXECUTE sp_executesql @cmd is commented out
Declare @Cmd nvarchar(max)
;with DistinctTables as
(
select distinct [RealTable], [StageTble] from MappingTable
),
InsertCommands as
(
select *,
'insert into ' + [RealTable] + '(' +
STUFF((
SELECT ',' + [RealCol]
FROM MappingTable t1
where t1.RealTable = drt.RealTable
ORDER BY OrdinalPosition
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'),1,1,'')
+ ')' +
' select ' +
STUFF((
SELECT ',' + [StageColumn]
FROM MappingTable t1
where t1.RealTable = drt.RealTable
ORDER BY OrdinalPosition
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'),1,1,'')
+ ' from ' + [StageTble] as InsertCommand
from DistinctTables drt
)
select @cmd =
STUFF((
SELECT ';' + char(10) + [InsertCommand]
FROM InsertCommands
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'),1,1,'')
+';' from InsertCommands ic
print @cmd
--EXECUTE sp_executesql @cmd
I cannot take all credit - this is also linked to post: SQL Insert via mappings table