SQL Server – Update All Tables Containing Column Name with Specific Field

sql serversql-server-2012

I know a similar question has been asked before but i was wonder if there is any way that you could run an update across all tables in a database where a column name exists but only for fields with a specific entry.

So for example UPDATE <table> SET <column_name> = '123' where <column_name> = '124'

Thanks in advance for everyones help

Best Answer

This answer will require some dynamic SQL and potentially could make use of a while/do loop.
Basically the idea will be to figure our how to define your list of tables and column names. If you really are just looking for a list of tables where a column name exists, you will probably want to make use of the sys.syscolumns table to query the column names.

SELECT o.name
FROM sys.syscolumns c
    JOIN sys.sysobjects o ON c.id=o.id
WHERE UPPER(c.name) = 'Description'

From there you can build your dynamic sql statement.

DECLARE @sqltext VARCHAR(MAX)
DECLARE @UpdateValue VARCHAR(30) = 'SetThisValue'

SELECT @sqltext = ISNULL(@sqltext,'') + 'UPDATE '+o.name + CHAR(10) + ' SET     [YourColumnNameHere] = ' + @UpdateValue + CHAR(10)
    + ' WHERE [YourColumnNameHere] = [Somevalue]'
FROM sys.syscolumns c
    JOIN sys.sysobjects o ON c.id=o.id
WHERE UPPER(c.name) = 'Description'

PRINT @sqltext
EXEC sp_executesql @sqltext

I have the print statement in there to help you get the @sqltext exactly the way you want it. Once you have it as you want, use the EXEC sp_executesql line to actually run the output of the @sqltext.