Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic update statement with variable column names

Tags:

We're looking to do an update in several SQL Server databases to change all NULL values in a certain table to be empty strings instead of NULL. We're potentially going to be doing this across hundreds of databases. The table name will always be the same, but the column names are variable based on how the front-end application is configured (don't judge... I didn't create this system).

Is there a way to do an update on all of these columns without knowing the column names ahead of time?

like image 523
jebar8 Avatar asked Oct 11 '12 19:10

jebar8


People also ask

Can I use CTE in dynamic SQL?

Using CTEs, for instance, you can use SELECT from <subquery> in Open SQL. In my case I needed to execute dynamic SELECT count( DISTINCT col1, col2, …) which is not possible in the regular OpenSQL.


2 Answers

You can pass the name of the column in dynamic sql:

declare @sql nvarchar (1000);
set @sql = N'update table set ' + @column_name + '= ''''';

exec sp_executesql @sql;
like image 51
tozka Avatar answered Sep 23 '22 15:09

tozka


You can look in the sys.columns table and join on the table name or object_id.

 DECLARE @OBJ_ID INT

 SELECT @OBJ_ID = OBJECT_ID
 FROM SYS.tables
 WHERE name = 'YOURTABLE'

 SELECT * FROM SYS.columns
 WHERE OBJECT_ID = @OBJ_ID

You could use the name field from the sys.columns query as a basis to perform the update on.

like image 41
Darren Avatar answered Sep 24 '22 15:09

Darren