﻿<?xml version='1.0' encoding='UTF-8'?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/"><channel><title>SQLServerCentral / Administering / SQL Server 2005  / Generate Update statements for an existing table / Latest Posts</title><generator>InstantForum.NET v2.9.0</generator><description>SQLServerCentral</description><link>http://www.sqlservercentral.com/Forums/</link><webMaster>notifications@sqlservercentral.com</webMaster><lastBuildDate>Tue, 21 May 2013 15:56:43 GMT</lastBuildDate><ttl>20</ttl><item><title>RE: Generate Update statements for an existing table</title><link>http://www.sqlservercentral.com/Forums/Topic820692-146-1.aspx</link><description>How we can ignore the timestamp field to generate statements in this script ?Please give some idea, how we can specify the specific columns for the generation of update statement. Thanks in Advance.</description><pubDate>Sun, 13 Jan 2013 00:27:11 GMT</pubDate><dc:creator>imrankasuri</dc:creator></item><item><title>RE: Generate Update statements for an existing table</title><link>http://www.sqlservercentral.com/Forums/Topic820692-146-1.aspx</link><description>Alex,Thanks for your response! This is a great help.ThanksKayal</description><pubDate>Thu, 19 Nov 2009 01:10:24 GMT</pubDate><dc:creator>Kayal</dc:creator></item><item><title>RE: Generate Update statements for an existing table</title><link>http://www.sqlservercentral.com/Forums/Topic820692-146-1.aspx</link><description>Here you go but you need to customize it for yourself. [code="plain"]  This script will generate script to insert/update from a source table in one database to an   identical destination table in another database or server.  It can be run for inserts or updates,  and can be run for a single row in insert and update mode, or all rows in a table for insert mode.*/declare @tab varchar(50)       ,@pk1Val varChar(10)	   ,@pk1Name varChar(50)	   ,@qt char(1)	   ,@StatementType varChar(10)set nocount on/* Instructions: 1) open script and connect to the source database 2) Change the  variable values to change the output options for the script below (@tab, @statementtype etc) 3) execute the script (best to use text output) 4) copy the script output into a script window, and run on the destination table.@Tab = the name of the source table@pk1Val = if selecting a single row or doing an update statement, the value of the primary key for that row@pk1Name = if inserting a single row or doing an update statement, the name of the column for the primary key@StatementType = either 'INSERT' to create an insert statement or 'UPDATE' for an Update statement*/select @tab = 'mytable', @pk1Val = '', @pk1Name = '', @StatementType = 'INSERT'declare @tabName varchar(50)      , @colName varchar(50)      , @colType varchar(50)       , @collength varChar(50)	  , @colOrder int	  , @IsIdent char(1)	create table #output (Line varChar(4000), LineOrder int)create table #ColumnValues (ColName varChar(250), ColOrder int, RowNumber int, ColValue varchar(4000), colType varchar(50))declare @out varchar(4000)       ,@lineCounter int	   ,@ColValue varchar(4000)	   ,@sortCol varchar(50)/* get the ordering column */select @sortCol = sc.Namefrom sysobjects soinner join syscolumns scon so.id=  sc.idinner join systypes ston sc.xtype = st.xusertype where so.Name = @tab and ((sc.status = 0x80) OR (ColOrder = 1 and not sc.status = 0x80 ))/* put in the repeating values based on the columns*/declare objCurs CURSOR FOR select so.name, sc.name, st.name, sc.length, Case when sc.status = 0x80 then 'Y' else 'N' END as IsIdent, ColOrderfrom sysobjects soinner join syscolumns scon so.id=  sc.idinner join systypes ston sc.xtype = st.xusertypewhere so.Name = @tabDECLARE @counter int, @numCols int, @RowNumber int, @LastRowNumber int, @maxRowNumber int, @maxColOrder intselect @numCols = count(sc.id) from sysobjects soinner join syscolumns scon so.id=  sc.idwhere so.Name = @tab--select @numCols  --debug codeopen objCursFetch from objCursinto @tabname, @colName, @colType, @colLength, @isIdent, @colOrderwhile @@fetch_status = 0begin	SET @counter = 0	/* get the value from the table */	if @IsIdent = 'N'	BEGIN	--select @TabName,@ColName, @ColType, @ColLEngth, @isIdent, @ColOrder  --debug code		/* increase better type handling by inserting more case statments, handling different data types */		if datalength(@pk1Name) = 0 or datalength(@pk1Val) = 0		begin			/* getting all rows in the table */			exec ('insert into #ColumnValues (ColName, ColOrder, ColValue, ColType) 					select  ''' + @colName + ''', ' + @ColOrder + ', Convert(nvarchar(4000),' + @colName + ') , ''' + @colType + ''' from ' + @tabName + ' order by ' + @SortCol + ' ' +				  ' declare @counter int set @counter = 0 ' +				  ' update #ColumnValues Set @Counter = RowNumber = @Counter + (' + @numCols + ' * 10) where ColName = ''' + @colName + '''' )		end		else		begin			/* filtering by a pk val */			exec ('insert into #ColumnValues (RowNumber, ColName, ColORder, ColValue, ColType)					select 0, ''' + @colName + ''', ' + @ColOrder + ', Convert(nvarchar(4000),' + @colName + ') , ''' + @colType + ''' from ' + @tabName + 				  ' where ' + @pk1Name + ' = ' + @pk1Val) 		end 	end /* if @isIdent = 'n' */	Fetch Next from objCurs	into @tabname, @colName, @colType, @colLength, @IsIdent, @ColOrderend --select * from #ColumnValues --debug codeselect @MaxRowNumber = Max(rowNumber) from #columnValues --keep highest row number so we know when we are finishedselect @MaxColOrder = max(ColOrder) from #ColumnValues where RowNumber = @MaxRowNumber/* next cursor for outputting the results from the retval table into the output table */declare ColVal_Curs  cursor forselect ColName , ColOrder , RowNumber , ColValue , colType from #ColumnValuesorder by RowNumber, ColOrderopen ColVal_Curs--set the last row number to the first in the table, so post loop checking worksselect @lastRowNumber = min(rowNumber) from #ColumnValues set @lineCounter = @LastRowNumber --initialise at the first rowfetch from ColVal_Curs into@colName, @ColOrder, @RowNumber, @colValue, @ColTypewhile @@Fetch_status = 0BEGIN /* cursor loop */		/* get the quote type to enclose the value from the column type */		select @qt = case @colType					 when 'nvarchar' then ''''					 when 'nchar' then ''''					 when 'DateTime' then ''''					 when 'ntext' then ''''					 else ''  					 end --select @linecounter, @colName, @ColOrder, @RowNumber, @colValue, @ColType		if not @ColValue is null 		if @rowNumber = @lineCounter			select @out = case @statementType							when  'UPDATE' THEN 'Update ' + @tab + ' SET '							when  'INSERT' then 'INSERT INTO ' + @tab + ' ('						  end 		begin			if @StatementType = 'UPDATE' 			BEGIN 				select @Out = @out + @colName + ' = ' + @qt + COALESCE(@ColValue, 'NULL') + @qt + ',' -- + @ColType 				insert into #output (Line, LineOrder)				values (@out, @lineCounter)			end 			if @statementType = 'INSERT' 			BEGIN 				/* put comma in */				if @lineCounter &amp;gt; @RowNumber --not first line in set of values for row					select @out = @out + ','								/*put in the name of the column */				insert into #output (Line, LineOrder)				values (@out + @colName					  , @lineCounter)				if @lineCounter &amp;gt; @RowNumber --not first line in set of values for row 					select @out = ','				else					select @out = ''				/* put in the value of the column */				insert into #output (Line, LineOrder)				values (@out + @qt + COALESCE(@ColValue, 'NULL') + @qt 					  , @lineCounter + 10 + @numCols)						END 		end  /*not @ColValue is null */	select @lineCounter = @lineCounter + 1	set @out = ''/* get the next record*/	fetch from ColVal_Curs into	@colName, @ColOrder, @RowNumber, @colValue, @ColType--select @ColOrder, @MaxColOrder, @@Fetch_Status  --debug code	if (@rowNumber &amp;gt; @lastRowNumber) or (@RowNumber = @MaxRowNumber and @MaxColOrder = @ColOrder and @@FEtch_Status = -1)	BEGIN	/* this bit of processing is done whenever the set of columsn in a row changes to the next row of the original table*/	/* ie we are building a record to insert, and the PK changes because we are at the next record */		/* remove the last comma from the last line */		declare @lastLine int		if @statementType = 'UPDATE'		begin			/*remove last comma*/			update #output			set Line = left(Line,datalength(Line)-1)			where lineOrder = @LineCounter			/* insert a 'where' clause */			insert into #output (line, LineOrder)			select ' WHERE ' + @pk1Name + ' = ' + @pk1Val, Max(LineOrder) + 1 from #output		end		if @statementType = 'INSERT'		BEGIN			/* put in a 'values' statement between the column names and the column values */			insert into #output (Line, LineOrder)			values (') VALUES (', @LastRowNumber + @numCols + 5)			/* close off the lot */			insert into #output (line, lineorder)			select ')', Max(LineOrder) + 1 from #output		END 		set @lastRowNumber = @RowNumber		set @lineCounter = @RowNumber  /* reset linecounter for next set */	End /* if rownumber &amp;gt; last row number */end /* cursor loop */close objCursdeallocate objCursclose ColVal_Cursdeallocate ColVal_Curs/* get the statements out from the list*/select line as [Copy script from output window below] from #output order by lineorder/*  bug tracking code - uncomment to diagnose problemsselect distinct RowNumber from #ColumnValues order by 1select * from #ColumnValuesorder by RowNumber, ColOrder, ColName, ColValue*/drop table #outputdrop table #ColumnValuesset nocount off[/code]</description><pubDate>Wed, 18 Nov 2009 16:12:04 GMT</pubDate><dc:creator>AlexSQLForums</dc:creator></item><item><title>Generate Update statements for an existing table</title><link>http://www.sqlservercentral.com/Forums/Topic820692-146-1.aspx</link><description>[b]Requirement:[/b]A SQL Script that can be used to generate the 'Update' Statements for a Table which has dataI found a superb piece of code @ http://www.keylimetie.com/blog/2009/3/24/sql-server-2005-script-to-generate-insert-statements for a 'Insert Statement Generator'. Well, call me lazy or a person who would not want to re-invent the wheel, Can anyone post their code if any that can generate Update statements for any given table.I do not want to specify the Primary Key Name or the Primary Key Value. The script should be able to pull the primary key and get the value from the existing rows. ;-)I have started working on this already, but thought it would be a good idea to post this in this intellectual forum! Thanks for your time to read through this. :-)[b]To be more specific:[/b]If I have a table with this structureCREATE TABLE [Address](	[AddressID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,	[AddressLine1] [nvarchar](60) NOT NULL,	[AddressLine2] [nvarchar](60) NULL,	[City] [nvarchar](30) NOT NULL, CONSTRAINT [PK_Address_AddressID] PRIMARY KEY CLUSTERED (	[AddressID] ASC))And it has the following dataINSERT INTO Address( [AddressID], [AddressLine1], [AddressLine2], [City])SELECT  32506, '5407 Cougar Way', ' ', 'Seattle'Go INSERT INTO Address( [AddressID], [AddressLine1], [AddressLine2], [City])SELECT  32507, '2284 Azalea Avenue', ' ', 'Bellevue'Go INSERT INTO Address( [AddressID], [AddressLine1], [AddressLine2], [City])SELECT  32508, '108 Lakeside Court', ' ', 'Bellevue'Go INSERT INTO Address( [AddressID], [AddressLine1], [AddressLine2], [City])SELECT  32509, '535 Greendell Pl', ' ', 'Sammamish'[b]This script should return the following output:[/b]Update Address SET AddressLine1 = '5407 Cougar Way',AddressLine2 = ' ',City = 'Seattle',WHERE  = 32506 Update Address SETAddressLine1 = '2284 Azalea Avenue',AddressLine2 = ' ',City = 'Bellevue',WHERE  = 32507 Update Address SET AddressLine1 = '108 Lakeside Court',AddressLine2 = ' ',City = 'Bellevue',WHERE  = 32508 Update Address SET AddressLine1 = '535 Greendell Pl',AddressLine2 = ' ',City = 'Sammamish',WHERE  = 32509[b]In case you have more time to read and guessing why I need this script?[/b]My current project is a SQL Server Migration project. A new version of the Application (V2) has been released and we are migrating data from the older version (V1) to (V2). The table schema has changed considerably between these 2 versions and we have a table where we maintain the Column Mapping details and couple of scripts that can dynamically generate the V2 Table Schema, Views and the Migration script also.There is a [b]special requirement[/b]  :w00t: where we are doing a 2-way Synchronization between 2 databases which have totally different structure - V1--&amp;gt;V2 and V2--&amp;gt;V1. We are right now implementing it by capturing all changes by triggers and logging it in to a Staging table and then a job runs which pushes the data either ways.After all these hard work, we are at the point of testing this Synchronization and we need a automated way to Generate Test Data.Since this is a 2 way Synch, we have a couple of test scenarios like the followingInsert rows into V1 tables Insert a row into a table. Update this row by changing the values of one or more columnsInsert a row into a table. Follow this up with a delete of the same rowUpdate an existing row in the V1 tableUpdate an existing row followed by a second updateUpdate an existing row followed by a deleteDelete an existing row from V1Delete an existing row from V1 followed by an insert with the same PK valueThe above 8 should result in these below 8The rows should get inserted in the corresponding V2 tablesThe row in V2 should reflect the changes done in the update statementThe row should not appear in V2The changes should get reflected in V2The changes of the second update should get reflected in  V2The row should be deleted from V2The row should get deleted from V2The new row should get inserted into V2 and the old row should not be presentThanksKayal</description><pubDate>Wed, 18 Nov 2009 03:59:52 GMT</pubDate><dc:creator>Kayal</dc:creator></item></channel></rss>