Dynamic update statement with variable column names
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;
Assuming you want all columns of varchar/char types only (or change the type filter to whatever you need):
DECLARE @tableName varchar(10)
SET @tableName = 'yourtablenamehere'
DECLARE @sql VARCHAR(MAX)
SET @sql = ''
SELECT @sql = @sql + 'UPDATE ' + @tableName + ' SET ' + c.name + ' = '''' WHERE ' + c.name + ' IS NULL ;'
FROM sys.columns c
INNER JOIN sys.tables t ON c.object_id = t.object_id
INNER JOIN sys.types y ON c.system_type_id = y.system_type_id
WHERE t.name = @tableName AND y.name IN ('varchar', 'nvarchar', 'char', 'nchar')
EXEC (@sql)
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.