Advertisement
trietnv

merge generate

Apr 5th, 2021
30
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 27.58 KB | None | 0 0
  1. SET NOCOUNT ON
  2. GO
  3.  
  4. PRINT 'Using Master database'
  5. USE master
  6. GO
  7.  
  8. PRINT 'Checking for the existence of this procedure'
  9. IF (SELECT OBJECT_ID('sp_generate_merge','P')) IS NOT NULL --means, the procedure already exists
  10. BEGIN
  11. PRINT 'Procedure already exists. So, dropping it'
  12. DROP PROC sp_generate_merge
  13. END
  14. GO
  15.  
  16. --Turn system object marking on
  17.  
  18. CREATE PROC [sp_generate_merge]
  19. (
  20. @table_name varchar(776), -- The table/view for which the MERGE statement will be generated using the existing data
  21. @target_table varchar(776) = NULL, -- Use this parameter to specify a different table name into which the data will be inserted/updated/deleted
  22. @from varchar(800) = NULL, -- Use this parameter to filter the rows based on a filter condition (using WHERE)
  23. @include_timestamp bit = 0, -- Specify 1 for this parameter, if you want to include the TIMESTAMP/ROWVERSION column's data in the MERGE statement
  24. @debug_mode bit = 0, -- If @debug_mode is set to 1, the SQL statements constructed by this procedure will be printed for later examination
  25. @schema varchar(64) = NULL, -- Use this parameter if you are not the owner of the table
  26. @ommit_images bit = 0, -- Use this parameter to generate MERGE statement by omitting the 'image' columns
  27. @ommit_identity bit = 0, -- Use this parameter to ommit the identity columns
  28. @top int = NULL, -- Use this parameter to generate a MERGE statement only for the TOP n rows
  29. @cols_to_include varchar(8000) = NULL, -- List of columns to be included in the MERGE statement
  30. @cols_to_exclude varchar(8000) = NULL, -- List of columns to be excluded from the MERGE statement
  31. @update_only_if_changed bit = 1, -- When 1, only performs an UPDATE operation if an included column in a matched row has changed.
  32. @delete_if_not_matched bit = 1, -- When 1, deletes unmatched source rows from target, when 0 source rows will only be used to update existing rows or insert new.
  33. @disable_constraints bit = 0, -- When 1, disables foreign key constraints and enables them after the MERGE statement
  34. @ommit_computed_cols bit = 0, -- When 1, computed columns will not be included in the MERGE statement
  35. @include_use_db bit = 1, -- When 1, includes a USE [DatabaseName] statement at the beginning of the generated batch
  36. @results_to_text bit = 0, -- When 1, outputs results to grid/messages window. When 0, outputs MERGE statement in an XML fragment.
  37. @include_rowsaffected bit = 1, -- When 1, a section is added to the end of the batch which outputs rows affected by the MERGE
  38. @nologo bit = 0, -- When 1, the "About" comment is suppressed from output
  39. @batch_separator VARCHAR(50) = 'GO' -- Batch separator to use
  40. )
  41. AS
  42. BEGIN
  43.  
  44. /***********************************************************************************************************
  45. Procedure: sp_generate_merge (Version 0.93)
  46. (Adapted by Daniel Nolan for SQL Server 2008/2012)
  47.  
  48. Adapted from: sp_generate_inserts (Build 22)
  49. (Copyright Β© 2002 Narayana Vyas Kondreddi. All rights reserved.)
  50.  
  51. Purpose: To generate a MERGE statement from existing data, which will INSERT/UPDATE/DELETE data based
  52. on matching primary key values in the source/target table.
  53.  
  54. The generated statements can be executed to replicate the data in some other location.
  55.  
  56. Typical use cases:
  57. * Generate statements for static data tables, store the .SQL file in source control and use
  58. it as part of your Dev/Test/Prod deployment. The generated statements are re-runnable, so
  59. you can make changes to the file and migrate those changes between environments.
  60.  
  61. * Generate statements from your Production tables and then run those statements in your
  62. Dev/Test environments. Schedule this as part of a SQL Job to keep all of your environments
  63. in-sync.
  64.  
  65. * Enter test data into your Dev environment, and then generate statements from the Dev
  66. tables so that you can always reproduce your test database with valid sample data.
  67.  
  68.  
  69. Written by: Narayana Vyas Kondreddi
  70. http://vyaskn.tripod.com
  71.  
  72. Daniel Nolan
  73. http://danere.com
  74. @dan3r3
  75.  
  76. Acknowledgements (sp_generate_merge):
  77. Nathan Skerl -- StackOverflow answer that provided a workaround for the output truncation problem
  78. http://stackoverflow.com/a/10489767/266882
  79.  
  80. Bill Gibson -- Blog that detailed the static data table use case; the inspiration for this proc
  81. http://blogs.msdn.com/b/ssdt/archive/2012/02/02/including-data-in-an-sql-server-database-project.aspx
  82.  
  83. Bill Graziano -- Blog that provided the groundwork for MERGE statement generation
  84. http://weblogs.sqlteam.com/billg/archive/2011/02/15/generate-merge-statements-from-a-table.aspx
  85.  
  86. Acknowledgements (sp_generate_inserts):
  87. Divya Kalra -- For beta testing
  88. Mark Charsley -- For reporting a problem with scripting uniqueidentifier columns with NULL values
  89. Artur Zeygman -- For helping me simplify a bit of code for handling non-dbo owned tables
  90. Joris Laperre -- For reporting a regression bug in handling text/ntext columns
  91.  
  92. Tested on: SQL Server 2008 (10.50.1600), SQL Server 2012 (11.0.2100)
  93.  
  94. Date created: January 17th 2001 21:52 GMT
  95. Modified: May 1st 2002 19:50 GMT
  96. Last Modified: September 27th 2012 10:00 AEDT
  97.  
  98. Email: dan@danere.com, vyaskn@hotmail.com
  99.  
  100. NOTE: This procedure may not work with tables with a large number of columns (> 500).
  101. Results can be unpredictable with huge text columns or SQL Server 2000's sql_variant data types
  102. IMPORTANT: This procedure has not been extensively tested with international data (Extended characters or Unicode). If needed
  103. you might want to convert the datatypes of character variables in this procedure to their respective unicode counterparts
  104. like nchar and nvarchar
  105.  
  106. Get Started: Ensure that your SQL client is configured to send results to grid (default SSMS behaviour).
  107. This ensures that the generated MERGE statement can be output in full, getting around SSMS's 4000 nchar limit.
  108. After running this proc, click the hyperlink within the single row returned to copy the generated MERGE statement.
  109.  
  110. Example 1: To generate a MERGE statement for table 'titles':
  111.  
  112. EXEC sp_generate_merge 'titles'
  113.  
  114. Example 2: To generate a MERGE statement for 'titlesCopy' table from 'titles' table:
  115.  
  116. EXEC sp_generate_merge 'titles', 'titlesCopy'
  117.  
  118. Example 3: To generate a MERGE statement for table 'titles' that will unconditionally UPDATE matching rows
  119. (ie. not perform a "has data changed?" check prior to going ahead with an UPDATE):
  120.  
  121. EXEC sp_generate_merge 'titles', @update_only_if_changed = 0
  122.  
  123. Example 4: To generate a MERGE statement for 'titles' table for only those titles
  124. which contain the word 'Computer' in them:
  125. NOTE: Do not complicate the FROM or WHERE clause here. It's assumed that you are good with T-SQL if you are using this parameter
  126.  
  127. EXEC sp_generate_merge 'titles', @from = "from titles where title like '%Computer%'"
  128.  
  129. Example 5: To specify that you want to include TIMESTAMP column's data as well in the MERGE statement:
  130. (By default TIMESTAMP column's data is not scripted)
  131.  
  132. EXEC sp_generate_merge 'titles', @include_timestamp = 1
  133.  
  134. Example 6: To print the debug information:
  135.  
  136. EXEC sp_generate_merge 'titles', @debug_mode = 1
  137.  
  138. Example 7: If the table is in a different schema to the default, use @schema parameter to specify the schema name
  139. To use this option, you must have SELECT permissions on that table
  140.  
  141. EXEC sp_generate_merge 'Nickstable', @schema = 'Nick'
  142.  
  143. Example 8: To generate a MERGE statement for the rest of the columns excluding images
  144.  
  145. EXEC sp_generate_merge 'imgtable', @ommit_images = 1
  146.  
  147. Example 9: To generate a MERGE statement excluding (omitting) IDENTITY columns:
  148. (By default IDENTITY columns are included in the MERGE statement)
  149.  
  150. EXEC sp_generate_merge 'mytable', @ommit_identity = 1
  151.  
  152. Example 10: To generate a MERGE statement for the TOP 10 rows in the table:
  153.  
  154. EXEC sp_generate_merge 'mytable', @top = 10
  155.  
  156. Example 11: To generate a MERGE statement with only those columns you want:
  157.  
  158. EXEC sp_generate_merge 'titles', @cols_to_include = "'title','title_id','au_id'"
  159.  
  160. Example 12: To generate a MERGE statement by omitting certain columns:
  161.  
  162. EXEC sp_generate_merge 'titles', @cols_to_exclude = "'title','title_id','au_id'"
  163.  
  164. Example 13: To avoid checking the foreign key constraints while loading data with a MERGE statement:
  165.  
  166. EXEC sp_generate_merge 'titles', @disable_constraints = 1
  167.  
  168. Example 14: To exclude computed columns from the MERGE statement:
  169.  
  170. EXEC sp_generate_merge 'MyTable', @ommit_computed_cols = 1
  171.  
  172. ***********************************************************************************************************/
  173.  
  174. SET NOCOUNT ON
  175.  
  176.  
  177. --Making sure user only uses either @cols_to_include or @cols_to_exclude
  178. IF ((@cols_to_include IS NOT NULL) AND (@cols_to_exclude IS NOT NULL))
  179. BEGIN
  180. RAISERROR('Use either @cols_to_include or @cols_to_exclude. Do not use both the parameters at once',16,1)
  181. RETURN -1 --Failure. Reason: Both @cols_to_include and @cols_to_exclude parameters are specified
  182. END
  183.  
  184.  
  185. --Making sure the @cols_to_include and @cols_to_exclude parameters are receiving values in proper format
  186. IF ((@cols_to_include IS NOT NULL) AND (PATINDEX('''%''',@cols_to_include) = 0))
  187. BEGIN
  188. RAISERROR('Invalid use of @cols_to_include property',16,1)
  189. PRINT 'Specify column names surrounded by single quotes and separated by commas'
  190. PRINT 'Eg: EXEC sp_generate_merge titles, @cols_to_include = "''title_id'',''title''"'
  191. RETURN -1 --Failure. Reason: Invalid use of @cols_to_include property
  192. END
  193.  
  194. IF ((@cols_to_exclude IS NOT NULL) AND (PATINDEX('''%''',@cols_to_exclude) = 0))
  195. BEGIN
  196. RAISERROR('Invalid use of @cols_to_exclude property',16,1)
  197. PRINT 'Specify column names surrounded by single quotes and separated by commas'
  198. PRINT 'Eg: EXEC sp_generate_merge titles, @cols_to_exclude = "''title_id'',''title''"'
  199. RETURN -1 --Failure. Reason: Invalid use of @cols_to_exclude property
  200. END
  201.  
  202.  
  203. --Checking to see if the database name is specified along wih the table name
  204. --Your database context should be local to the table for which you want to generate a MERGE statement
  205. --specifying the database name is not allowed
  206. IF (PARSENAME(@table_name,3)) IS NOT NULL
  207. BEGIN
  208. RAISERROR('Do not specify the database name. Be in the required database and just specify the table name.',16,1)
  209. RETURN -1 --Failure. Reason: Database name is specified along with the table name, which is not allowed
  210. END
  211.  
  212.  
  213. --Checking for the existence of 'user table' or 'view'
  214. --This procedure is not written to work on system tables
  215. --To script the data in system tables, just create a view on the system tables and script the view instead
  216. IF @schema IS NULL
  217. BEGIN
  218. IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = @table_name AND (TABLE_TYPE = 'BASE TABLE' OR TABLE_TYPE = 'VIEW') AND TABLE_SCHEMA = SCHEMA_NAME())
  219. BEGIN
  220. RAISERROR('User table or view not found.',16,1)
  221. PRINT 'You may see this error if the specified table is not in your default schema (' + SCHEMA_NAME() + '). In that case use @schema parameter to specify the schema name.'
  222. PRINT 'Make sure you have SELECT permission on that table or view.'
  223. RETURN -1 --Failure. Reason: There is no user table or view with this name
  224. END
  225. END
  226. ELSE
  227. BEGIN
  228. IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = @table_name AND (TABLE_TYPE = 'BASE TABLE' OR TABLE_TYPE = 'VIEW') AND TABLE_SCHEMA = @schema)
  229. BEGIN
  230. RAISERROR('User table or view not found.',16,1)
  231. PRINT 'Make sure you have SELECT permission on that table or view.'
  232. RETURN -1 --Failure. Reason: There is no user table or view with this name
  233. END
  234. END
  235.  
  236.  
  237. --Variable declarations
  238. DECLARE @Column_ID int,
  239. @Column_List varchar(8000),
  240. @Column_List_For_Update varchar(8000),
  241. @Column_List_For_Check varchar(8000),
  242. @Column_Name varchar(128),
  243. @Column_Name_Unquoted varchar(128),
  244. @Data_Type varchar(128),
  245. @Actual_Values nvarchar(max), --This is the string that will be finally executed to generate a MERGE statement
  246. @IDN varchar(128), --Will contain the IDENTITY column's name in the table
  247. @Target_Table_For_Output varchar(776),
  248. @Source_Table_Qualified varchar(776)
  249.  
  250.  
  251.  
  252. --Variable Initialization
  253. SET @IDN = ''
  254. SET @Column_ID = 0
  255. SET @Column_Name = ''
  256. SET @Column_Name_Unquoted = ''
  257. SET @Column_List = ''
  258. SET @Column_List_For_Update = ''
  259. SET @Column_List_For_Check = ''
  260. SET @Actual_Values = ''
  261.  
  262. --Variable Defaults
  263. IF @schema IS NULL
  264. BEGIN
  265. SET @Target_Table_For_Output = QUOTENAME(COALESCE(@target_table, @table_name))
  266. END
  267. ELSE
  268. BEGIN
  269. SET @Target_Table_For_Output = QUOTENAME(@schema) + '.' + QUOTENAME(COALESCE(@target_table, @table_name))
  270. END
  271.  
  272. SET @Source_Table_Qualified = QUOTENAME(COALESCE(@schema,SCHEMA_NAME())) + '.' + QUOTENAME(@table_name)
  273.  
  274. --To get the first column's ID
  275. SELECT @Column_ID = MIN(ORDINAL_POSITION)
  276. FROM INFORMATION_SCHEMA.COLUMNS (NOLOCK)
  277. WHERE TABLE_NAME = @table_name
  278. AND TABLE_SCHEMA = COALESCE(@schema, SCHEMA_NAME())
  279.  
  280.  
  281. --Loop through all the columns of the table, to get the column names and their data types
  282. WHILE @Column_ID IS NOT NULL
  283. BEGIN
  284. SELECT @Column_Name = QUOTENAME(COLUMN_NAME),
  285. @Column_Name_Unquoted = COLUMN_NAME,
  286. @Data_Type = DATA_TYPE
  287. FROM INFORMATION_SCHEMA.COLUMNS (NOLOCK)
  288. WHERE ORDINAL_POSITION = @Column_ID
  289. AND TABLE_NAME = @table_name
  290. AND TABLE_SCHEMA = COALESCE(@schema, SCHEMA_NAME())
  291.  
  292. IF @cols_to_include IS NOT NULL --Selecting only user specified columns
  293. BEGIN
  294. IF CHARINDEX( '''' + SUBSTRING(@Column_Name,2,LEN(@Column_Name)-2) + '''',@cols_to_include) = 0
  295. BEGIN
  296. GOTO SKIP_LOOP
  297. END
  298. END
  299.  
  300. IF @cols_to_exclude IS NOT NULL --Selecting only user specified columns
  301. BEGIN
  302. IF CHARINDEX( '''' + SUBSTRING(@Column_Name,2,LEN(@Column_Name)-2) + '''',@cols_to_exclude) <> 0
  303. BEGIN
  304. GOTO SKIP_LOOP
  305. END
  306. END
  307.  
  308. --Making sure to output SET IDENTITY_INSERT ON/OFF in case the table has an IDENTITY column
  309. IF (SELECT COLUMNPROPERTY( OBJECT_ID(@Source_Table_Qualified),SUBSTRING(@Column_Name,2,LEN(@Column_Name) - 2),'IsIdentity')) = 1
  310. BEGIN
  311. IF @ommit_identity = 0 --Determing whether to include or exclude the IDENTITY column
  312. SET @IDN = @Column_Name
  313. ELSE
  314. GOTO SKIP_LOOP
  315. END
  316.  
  317. --Making sure whether to output computed columns or not
  318. IF @ommit_computed_cols = 1
  319. BEGIN
  320. IF (SELECT COLUMNPROPERTY( OBJECT_ID(@Source_Table_Qualified),SUBSTRING(@Column_Name,2,LEN(@Column_Name) - 2),'IsComputed')) = 1
  321. BEGIN
  322. GOTO SKIP_LOOP
  323. END
  324. END
  325.  
  326. --Tables with columns of IMAGE data type are not supported for obvious reasons
  327. IF(@Data_Type in ('image'))
  328. BEGIN
  329. IF (@ommit_images = 0)
  330. BEGIN
  331. RAISERROR('Tables with image columns are not supported.',16,1)
  332. PRINT 'Use @ommit_images = 1 parameter to generate a MERGE for the rest of the columns.'
  333. RETURN -1 --Failure. Reason: There is a column with image data type
  334. END
  335. ELSE
  336. BEGIN
  337. GOTO SKIP_LOOP
  338. END
  339. END
  340.  
  341. --Determining the data type of the column and depending on the data type, the VALUES part of
  342. --the MERGE statement is generated. Care is taken to handle columns with NULL values. Also
  343. --making sure, not to lose any data from flot, real, money, smallmomey, datetime columns
  344. SET @Actual_Values = @Actual_Values +
  345. CASE
  346. WHEN @Data_Type IN ('char','nchar')
  347. THEN
  348. 'COALESCE(''N'''''' + REPLACE(RTRIM(' + @Column_Name + '),'''''''','''''''''''')+'''''''',''NULL'')'
  349. WHEN @Data_Type IN ('varchar','nvarchar')
  350. THEN
  351. 'COALESCE(''N'''''' + REPLACE(' + @Column_Name + ','''''''','''''''''''')+'''''''',''NULL'')'
  352. WHEN @Data_Type IN ('datetime','smalldatetime','datetime2','date')
  353. THEN
  354. 'COALESCE('''''''' + RTRIM(CONVERT(char,' + @Column_Name + ',127))+'''''''',''NULL'')'
  355. WHEN @Data_Type IN ('uniqueidentifier')
  356. THEN
  357. 'COALESCE(''N'''''' + REPLACE(CONVERT(char(36),RTRIM(' + @Column_Name + ')),'''''''','''''''''''')+'''''''',''NULL'')'
  358. WHEN @Data_Type IN ('text')
  359. THEN
  360. 'COALESCE(''N'''''' + REPLACE(CONVERT(varchar(max),' + @Column_Name + '),'''''''','''''''''''')+'''''''',''NULL'')'
  361. WHEN @Data_Type IN ('ntext')
  362. THEN
  363. 'COALESCE('''''''' + REPLACE(CONVERT(nvarchar(max),' + @Column_Name + '),'''''''','''''''''''')+'''''''',''NULL'')'
  364. WHEN @Data_Type IN ('xml')
  365. THEN
  366. 'COALESCE('''''''' + REPLACE(CONVERT(nvarchar(max),' + @Column_Name + '),'''''''','''''''''''')+'''''''',''NULL'')'
  367. WHEN @Data_Type IN ('binary','varbinary')
  368. THEN
  369. 'COALESCE(RTRIM(CONVERT(varchar(max),' + @Column_Name + ', 1))),''NULL'')'
  370. WHEN @Data_Type IN ('timestamp','rowversion')
  371. THEN
  372. CASE
  373. WHEN @include_timestamp = 0
  374. THEN
  375. '''DEFAULT'''
  376. ELSE
  377. 'COALESCE(RTRIM(CONVERT(char,' + 'CONVERT(int,' + @Column_Name + '))),''NULL'')'
  378. END
  379. WHEN @Data_Type IN ('float','real','money','smallmoney')
  380. THEN
  381. 'COALESCE(LTRIM(RTRIM(' + 'CONVERT(char, ' + @Column_Name + ',2)' + ')),''NULL'')'
  382. WHEN @Data_Type IN ('hierarchyid')
  383. THEN
  384. 'COALESCE(''hierarchyid::Parse(''+'''''''' + LTRIM(RTRIM(' + 'CONVERT(char, ' + @Column_Name + ')' + '))+''''''''+'')'',''NULL'')'
  385. ELSE
  386. 'COALESCE(LTRIM(RTRIM(' + 'CONVERT(char, ' + @Column_Name + ')' + ')),''NULL'')'
  387. END + '+' + ''',''' + ' + '
  388.  
  389. --Generating the column list for the MERGE statement
  390. SET @Column_List = @Column_List + @Column_Name + ','
  391.  
  392. --Don't update Primary Key or Identity columns
  393. IF NOT EXISTS(
  394. SELECT 1
  395. FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,
  396. INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
  397. WHERE pk.TABLE_NAME = @table_name
  398. AND pk.TABLE_SCHEMA = COALESCE(@schema, SCHEMA_NAME())
  399. AND CONSTRAINT_TYPE = 'PRIMARY KEY'
  400. AND c.TABLE_NAME = pk.TABLE_NAME
  401. AND c.TABLE_SCHEMA = pk.TABLE_SCHEMA
  402. AND c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME
  403. AND c.COLUMN_NAME = @Column_Name_Unquoted
  404. )
  405. BEGIN
  406. SET @Column_List_For_Update = @Column_List_For_Update + @Column_Name + ' = Source.' + @Column_Name + ',
  407. '
  408. SET @Column_List_For_Check = @Column_List_For_Check +
  409. CASE @Data_Type
  410. WHEN 'text' THEN CHAR(10) + CHAR(9) + 'NULLIF(CAST(Source.' + @Column_Name + ' AS VARCHAR(MAX)), CAST(Target.' + @Column_Name + ' AS VARCHAR(MAX))) IS NOT NULL OR NULLIF(CAST(Target.' + @Column_Name + ' AS VARCHAR(MAX)), CAST(Source.' + @Column_Name + ' AS VARCHAR(MAX))) IS NOT NULL OR '
  411. WHEN 'ntext' THEN CHAR(10) + CHAR(9) + 'NULLIF(CAST(Source.' + @Column_Name + ' AS NVARCHAR(MAX)), CAST(Target.' + @Column_Name + ' AS NVARCHAR(MAX))) IS NOT NULL OR NULLIF(CAST(Target.' + @Column_Name + ' AS NVARCHAR(MAX)), CAST(Source.' + @Column_Name + ' AS NVARCHAR(MAX))) IS NOT NULL OR '
  412. ELSE CHAR(10) + CHAR(9) + 'NULLIF(Source.' + @Column_Name + ', Target.' + @Column_Name + ') IS NOT NULL OR NULLIF(Target.' + @Column_Name + ', Source.' + @Column_Name + ') IS NOT NULL OR '
  413. END
  414. END
  415.  
  416. SKIP_LOOP: --The label used in GOTO
  417.  
  418. SELECT @Column_ID = MIN(ORDINAL_POSITION)
  419. FROM INFORMATION_SCHEMA.COLUMNS (NOLOCK)
  420. WHERE TABLE_NAME = @table_name
  421. AND TABLE_SCHEMA = COALESCE(@schema, SCHEMA_NAME())
  422. AND ORDINAL_POSITION > @Column_ID
  423.  
  424. END --Loop ends here!
  425.  
  426.  
  427. --To get rid of the extra characters that got concatenated during the last run through the loop
  428. IF LEN(@Column_List_For_Update) <> 0
  429. BEGIN
  430. SET @Column_List_For_Update = ' ' + LEFT(@Column_List_For_Update,len(@Column_List_For_Update) - 4)
  431. END
  432.  
  433. IF LEN(@Column_List_For_Check) <> 0
  434. BEGIN
  435. SET @Column_List_For_Check = LEFT(@Column_List_For_Check,len(@Column_List_For_Check) - 3)
  436. END
  437.  
  438. SET @Actual_Values = LEFT(@Actual_Values,len(@Actual_Values) - 6)
  439.  
  440. SET @Column_List = LEFT(@Column_List,len(@Column_List) - 1)
  441. IF LEN(LTRIM(@Column_List)) = 0
  442. BEGIN
  443. RAISERROR('No columns to select. There should at least be one column to generate the output',16,1)
  444. RETURN -1 --Failure. Reason: Looks like all the columns are ommitted using the @cols_to_exclude parameter
  445. END
  446.  
  447.  
  448. --Get the join columns ----------------------------------------------------------
  449. DECLARE @PK_column_list VARCHAR(8000)
  450. DECLARE @PK_column_joins VARCHAR(8000)
  451. SET @PK_column_list = ''
  452. SET @PK_column_joins = ''
  453.  
  454. SELECT @PK_column_list = @PK_column_list + '[' + c.COLUMN_NAME + '], '
  455. , @PK_column_joins = @PK_column_joins + 'Target.[' + c.COLUMN_NAME + '] = Source.[' + c.COLUMN_NAME + '] AND '
  456. FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,
  457. INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
  458. WHERE pk.TABLE_NAME = @table_name
  459. AND pk.TABLE_SCHEMA = COALESCE(@schema, SCHEMA_NAME())
  460. AND CONSTRAINT_TYPE = 'PRIMARY KEY'
  461. AND c.TABLE_NAME = pk.TABLE_NAME
  462. AND c.TABLE_SCHEMA = pk.TABLE_SCHEMA
  463. AND c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME
  464.  
  465. IF IsNull(@PK_column_list, '') = ''
  466. BEGIN
  467. RAISERROR('Table has no primary keys. There should at least be one column in order to have a valid join.',16,1)
  468. RETURN -1 --Failure. Reason: looks like table doesn't have any primary keys
  469. END
  470.  
  471. SET @PK_column_list = LEFT(@PK_column_list, LEN(@PK_column_list) -1)
  472. SET @PK_column_joins = LEFT(@PK_column_joins, LEN(@PK_column_joins) -4)
  473.  
  474.  
  475. --Forming the final string that will be executed, to output the a MERGE statement
  476. SET @Actual_Values =
  477. 'SELECT ' +
  478. CASE WHEN @top IS NULL OR @top < 0 THEN '' ELSE ' TOP ' + LTRIM(STR(@top)) + ' ' END +
  479. '''' +
  480. ' '' + CASE WHEN ROW_NUMBER() OVER (ORDER BY ' + @PK_column_list + ') = 1 THEN '' '' ELSE '','' END + ''(''+ ' + @Actual_Values + '+'')''' + ' ' +
  481. COALESCE(@from,' FROM ' + @Source_Table_Qualified + ' (NOLOCK) ORDER BY ' + @PK_column_list)
  482.  
  483. DECLARE @output VARCHAR(MAX) = ''
  484. DECLARE @b CHAR(1) = CHAR(13)
  485.  
  486. --Determining whether to ouput any debug information
  487. IF @debug_mode =1
  488. BEGIN
  489. SET @output += @b + '/*****START OF DEBUG INFORMATION*****'
  490. SET @output += @b + ''
  491. SET @output += @b + 'The primary key column list:'
  492. SET @output += @b + @PK_column_list
  493. SET @output += @b + ''
  494. SET @output += @b + 'The INSERT column list:'
  495. SET @output += @b + @Column_List
  496. SET @output += @b + ''
  497. SET @output += @b + 'The UPDATE column list:'
  498. SET @output += @b + @Column_List_For_Update
  499. SET @output += @b + ''
  500. SET @output += @b + 'The SELECT statement executed to generate the MERGE:'
  501. SET @output += @b + @Actual_Values
  502. SET @output += @b + ''
  503. SET @output += @b + '*****END OF DEBUG INFORMATION*****/'
  504. SET @output += @b + ''
  505. END
  506.  
  507. IF (@include_use_db = 1)
  508. BEGIN
  509. SET @output += 'USE ' + DB_NAME()
  510. SET @output += @b + @batch_separator
  511. SET @output += @b + @b
  512. END
  513.  
  514. IF (@nologo = 0)
  515. BEGIN
  516. SET @output += @b + '--MERGE generated by ''sp_generate_merge'' stored procedure, Version 0.93'
  517. SET @output += @b + '--Originally by Vyas (http://vyaskn.tripod.com): sp_generate_inserts (build 22)'
  518. SET @output += @b + '--Adapted for SQL Server 2008/2012 by Daniel Nolan (http://danere.com)'
  519. SET @output += @b + ''
  520. END
  521.  
  522. IF (@include_rowsaffected = 1) -- If the caller has elected not to include the "rows affected" section, let MERGE output the row count as it is executed.
  523. SET @output += @b + 'SET NOCOUNT ON'
  524. SET @output += @b + ''
  525.  
  526.  
  527. --Determining whether to print IDENTITY_INSERT or not
  528. IF (LEN(@IDN) <> 0)
  529. BEGIN
  530. SET @output += @b + 'SET IDENTITY_INSERT ' + @Target_Table_For_Output + ' ON'
  531. SET @output += @b + ''
  532. END
  533.  
  534.  
  535. --Temporarily disable constraints on the target table
  536. IF @disable_constraints = 1 AND (OBJECT_ID(@Source_Table_Qualified, 'U') IS NOT NULL)
  537. BEGIN
  538. SET @output += @b + 'ALTER TABLE ' + @Target_Table_For_Output + ' NOCHECK CONSTRAINT ALL' --Code to disable constraints temporarily
  539. END
  540.  
  541.  
  542. --Output the start of the MERGE statement, qualifying with the schema name only if the caller explicitly specified it
  543. SET @output += @b + 'MERGE INTO ' + @Target_Table_For_Output + ' AS Target'
  544. SET @output += @b + 'USING (VALUES'
  545.  
  546.  
  547. --All the hard work pays off here!!! You'll get your MERGE statement, when the next line executes!
  548. DECLARE @tab TABLE (ID INT NOT NULL PRIMARY KEY IDENTITY(1,1), val NVARCHAR(max));
  549. INSERT INTO @tab (val)
  550. EXEC (@Actual_Values)
  551.  
  552. IF (SELECT COUNT(*) FROM @tab) <> 0 -- Ensure that rows were returned, otherwise the MERGE statement will get nullified.
  553. BEGIN
  554. SET @output += CAST((SELECT @b + val FROM @tab ORDER BY ID FOR XML PATH('')) AS XML).value('.', 'VARCHAR(MAX)');
  555. END
  556.  
  557. --Output the columns to correspond with each of the values above--------------------
  558. SET @output += @b + ') AS Source (' + @Column_List + ')'
  559.  
  560.  
  561. --Output the join columns ----------------------------------------------------------
  562. SET @output += @b + 'ON (' + @PK_column_joins + ')'
  563.  
  564.  
  565. --When matched, perform an UPDATE on any metadata columns only (ie. not on PK)------
  566. IF LEN(@Column_List_For_Update) <> 0
  567. BEGIN
  568. SET @output += @b + 'WHEN MATCHED ' + CASE WHEN @update_only_if_changed = 1 THEN 'AND (' + @Column_List_For_Check + ') ' ELSE '' END + 'THEN'
  569. SET @output += @b + ' UPDATE SET'
  570. SET @output += @b + ' ' + LTRIM(@Column_List_For_Update)
  571. END
  572.  
  573.  
  574. --When NOT matched by target, perform an INSERT------------------------------------
  575. SET @output += @b + 'WHEN NOT MATCHED BY TARGET THEN';
  576. SET @output += @b + ' INSERT(' + @Column_List + ')'
  577. SET @output += @b + ' VALUES(' + REPLACE(@Column_List, '[', 'Source.[') + ')'
  578.  
  579.  
  580. --When NOT matched by source, DELETE the row
  581. IF @delete_if_not_matched=1 BEGIN
  582. SET @output += @b + 'WHEN NOT MATCHED BY SOURCE THEN '
  583. SET @output += @b + ' DELETE'
  584. END;
  585. SET @output += @b + ';'
  586. SET @output += @b + @batch_separator
  587.  
  588. --Display the number of affected rows to the user, or report if an error occurred---
  589. IF @include_rowsaffected = 1
  590. BEGIN
  591. SET @output += @b + 'DECLARE @mergeError int'
  592. SET @output += @b + ' , @mergeCount int'
  593. SET @output += @b + 'SELECT @mergeError = @@ERROR, @mergeCount = @@ROWCOUNT'
  594. SET @output += @b + 'IF @mergeError != 0'
  595. SET @output += @b + ' BEGIN'
  596. SET @output += @b + ' PRINT ''ERROR OCCURRED IN MERGE FOR ' + @Target_Table_For_Output + '. Rows affected: '' + CAST(@mergeCount AS VARCHAR(100)); -- SQL should always return zero rows affected';
  597. SET @output += @b + ' END'
  598. SET @output += @b + 'ELSE'
  599. SET @output += @b + ' BEGIN'
  600. SET @output += @b + ' PRINT ''' + @Target_Table_For_Output + ' rows affected by MERGE: '' + CAST(@mergeCount AS VARCHAR(100));';
  601. SET @output += @b + ' END'
  602. SET @output += @b + @batch_separator
  603. SET @output += @b + @b
  604. END
  605.  
  606. --Re-enable the previously disabled constraints-------------------------------------
  607. IF @disable_constraints = 1 AND (OBJECT_ID(@Source_Table_Qualified, 'U') IS NOT NULL)
  608. BEGIN
  609. SET @output += 'ALTER TABLE ' + @Target_Table_For_Output + ' CHECK CONSTRAINT ALL' --Code to enable the previously disabled constraints
  610. SET @output += @b + @batch_separator
  611. SET @output += @b
  612. END
  613.  
  614.  
  615. --Switch-off identity inserting------------------------------------------------------
  616. IF (LEN(@IDN) <> 0)
  617. BEGIN
  618. SET @output += 'SET IDENTITY_INSERT ' + @Target_Table_For_Output + ' OFF'
  619. SET @output += @b + @batch_separator
  620. SET @output += @b
  621. END
  622.  
  623. IF (@include_rowsaffected = 1)
  624. BEGIN
  625. SET @output += 'SET NOCOUNT OFF'
  626. SET @output += @b + @batch_separator
  627. SET @output += @b
  628. END
  629.  
  630. SET @output += @b + ''
  631. SET @output += @b + ''
  632.  
  633. IF @results_to_text = 1
  634. BEGIN
  635. --output the statement to the Grid/Messages tab
  636. SELECT @output;
  637. END
  638. ELSE
  639. BEGIN
  640. --output the statement as xml (to overcome SSMS 4000/8000 char limitation)
  641. SELECT [processing-instruction(x)]=@output FOR XML PATH(''),TYPE;
  642. PRINT 'MERGE statement has been wrapped in an XML fragment and output successfully.'
  643. PRINT 'Ensure you have Results to Grid enabled and then click the hyperlink to copy the statement within the fragment.'
  644. PRINT ''
  645. PRINT 'If you would prefer to have results output directly (without XML) specify @results_to_text = 1, however please'
  646. PRINT 'note that the results may be truncated by your SQL client to 4000 nchars.'
  647. END
  648.  
  649. SET NOCOUNT OFF
  650. RETURN 0 --Success. We are done!
  651. END
  652.  
  653. GO
  654.  
  655. PRINT 'Created the procedure'
  656. GO
  657.  
  658.  
  659. --Mark the proc as a system object to allow it to be called transparently from other databases
  660. EXEC sp_MS_marksystemobject sp_generate_merge
  661. GO
  662.  
  663. PRINT 'Granting EXECUTE permission on sp_generate_merge to all users'
  664. GRANT EXEC ON sp_generate_merge TO public
  665.  
  666. SET NOCOUNT OFF
  667. GO
  668.  
  669. PRINT 'Done'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement