Guest User

Untitled

a guest
Dec 12th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. Declare @Cmd nvarchar(max)
  2. ;with DistinctTables as
  3. (
  4. select distinct [DestTable], [SourceFile] from [tbl_IN_Ctrl_Dtl]
  5. ),
  6. InsertCommands as
  7. (
  8. -- columns from Destination table
  9. select *,
  10. 'BEGIN TRY insert into ' + [DestTable] + '(' +
  11. STUFF((
  12. SELECT ',' + [DestCol]
  13. FROM [tbl_IN_Ctrl_Dtl] t1
  14. where t1.DestTable = drt.DestTable
  15. GROUP BY DestCol,ORDINAL_POSITION
  16. ORDER BY ORDINAL_POSITION
  17. FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'),1,1,'')
  18. + ')' +
  19. ' select ' +
  20. -- columns from source table
  21. STUFF((
  22. SELECT ',' + [SourceCol]
  23. FROM [tbl_IN_Ctrl_Dtl] t1
  24. where t1.DestTable = drt.DestTable
  25. GROUP BY SourceCol,ORDINAL_POSITION
  26. ORDER BY ORDINAL_POSITION
  27. FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'),1,1,'')
  28. + ' from ' + [SourceFile]
  29. + ';
  30. update tbl_IN_Ctrl_Header set ErrMsg = @@ERROR where SourceFile_INSERT = 0 and SourceFile = ''' + [SourceFile]+ ''''
  31. +';
  32. update tbl_IN_Ctrl_Header set SourceFile_INSERT = 1 where SourceFile_INSERT = 0 and SourceFile = ''' + [SourceFile]+ ''''
  33. +'; END TRY BEGIN CATCH'
  34. as InsertCommand
  35. from DistinctTables drt
  36. )
  37. select @cmd =
  38. STUFF((
  39. SELECT ';' + char(10) + [InsertCommand]
  40. FROM InsertCommands
  41. FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'),1,1,'')
  42. +';' from InsertCommands ic
  43.  
  44. --print @cmd
  45.  
  46. EXECUTE sp_executesql @cmd
  47.  
  48. update tbl_IN_Ctrl_Header set ErrMsg = @@ERROR where SourceFile_INSERT = 0 and SourceFile = ''' + [SourceFile]+ ''''
Add Comment
Please, Sign In to add comment