Link to home
Start Free TrialLog in
Avatar of wdbates
wdbatesFlag for United States of America

asked on

Updating columns in all tables in a SQL 2008r2 database

Dear Expert;

I need to update 2 columns in all tables in a database where these columns are blank or NULL.  These 2 columns are CreatedBy and CreatedOn where CreatedBy = ‘System’ and CreatedOn = GETDATE().  I can obtain the SCHEMA and TABLE name where these columns are present with the following query:

select c.TABLE_SCHEMA, c.TABLE_NAME
from information_schema.columns c
INNER JOIN information_schema.TABLES t ON c.TABLE_NAME = t.TABLE_NAME  
WHERE t.TABLE_TYPE = 'BASE TABLE' AND COLUMN_NAME = 'CreatedOn'

How do I loop through this list and update the columns with the default values?  I suspect using a CTE with the list of SCHEMAs and TABLEs is a good starting place.
Avatar of Jim Horn
Jim Horn
Flag of United States of America image

That will require a cursor.  Using your SQL statement above, give this a whirl..

Declare @schema_name varchar(10), @table_name varchar(50) , @sql nvarchar(1000) 

Declare @getdate datetime = GETDATE()
Declare @getdate_vc varchar(50) = CONVERT(varchar, @getdate, 121) 

-- Delete all rows from these tables
DECLARE cur Cursor 
FOR 
select c.TABLE_SCHEMA, c.TABLE_NAME
from information_schema.columns c
	JOIN information_schema.TABLES t ON c.TABLE_NAME = t.TABLE_NAME  
WHERE t.TABLE_TYPE = 'BASE TABLE' AND COLUMN_NAME = 'CreatedOn'

FETCH NEXT FROM cur INTO @schema_name, @table_name
WHILE (@@FETCH_STATUS <> -1)  
	BEGIN
	IF (@@FETCH_STATUS <> -2)

		SELECT @sql = 'UPDATE ' + @schema_name + '.' + @table_name + ' '
		SELECT @sql = @sql + 'SET CreatedBy=''system'', CreatedOn=''' + @getdate_vc + ''' '
		SELECT @sql = @sql + 'WHERE ISNULL(CreatedOn, '''') = '''''

		-- At first run with the below line enabled to make sure the T-SQL is correct
		SELECT @sql

		-- Then run with the below line enabled to execute
		-- exec sp_executesql @sql

	FETCH NEXT FROM cur INTO @schema_name, @table_name	
	END
CLOSE cur
DEALLOCATE cur

Open in new window

Avatar of wdbates

ASKER

Msg 16916, Level 16, State 1, Line 9
A cursor with the name 'mycur' does not exist.
Msg 16917, Level 16, State 2, Line 16
Cursor is not open.
Msg 16917, Level 16, State 1, Line 33
Cursor is not open.
ASKER CERTIFIED SOLUTION
Avatar of Scott Pletcher
Scott Pletcher
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of wdbates

ASKER

Scott, one of the best solutions I've ever seen.  Thank you!
Thank you too for the very nice comment!