在SQL Server的所有列中更新(查找和替换)

时间:2016-06-23 08:36:50

标签: sql sql-server

我在表中获得了更新数据的脚本:

update [dbo].[temp_LABORATOR_copy]
set [PRA] = replace([PRA], '.', ',');
update [dbo].[temp_LABORATOR_copy]
set [PRV] = replace([PRV], '.', ',');
update [dbo].[temp_LABORATOR_copy]
set [TVK] = replace([TVK], '.', ',');
update [dbo].[temp_LABORATOR_copy]
set [eAl] = replace([eAl], '.', ',');
update [dbo].[temp_LABORATOR_copy]
set [efH] = replace([efH], '.', ',');

但表中有53列,每列的列表脚本分别效率低下。是否有可能全面地为整个表执行此脚本?

喜欢:

update [dbo].[temp_LABORATOR_copy]
set * = NULL
where * like '***'

2 个答案:

答案 0 :(得分:1)

生成像这样的脚本使用动态sql。

DECLARE @tableName varchar(50) = '[dbo].[temp_LABORATOR_copy]'
DECLARE @sql VARCHAR(MAX)='';

-- columns
SELECT @sql = @sql 
   + CASE len(@sql) WHEN 0 THEN '' ELSE ',' END 
   + c.name + ' = CASE WHEN ' + c.name +  ' LIKE ''***'' THEN NULL ELSE '  + c.name + ' END'
FROM sys.columns c
WHERE c.object_id = OBJECT_ID(@tableName)

SET @sql = 'UPDATE ' + @tableName + ' SET ' +@sql ;

select @sql;

EXECUTE (@sql);

答案 1 :(得分:0)

您可以使用动态SQL:

DECLARE @sql nvarchar(max)

SELECT @sql = (
SELECT 'update [dbo].[temp_LABORATOR_copy] set [' +COLUMN_NAME+'] = replace(['+COLUMN_NAME+'], ''.'', '','');'
FROM information_schema.columns
WHERE TABLE_NAME = 'temp_LABORATOR_copy'
AND COLUMN_NAME NOT IN ('Field2','Field3') -- Here put columns that must not be updated
AND DATA_TYPE IN ('nvarchar','varchar','nchar','char')
FOR XML PATH('')
)
--That will give you script like
--update [dbo].[temp_LABORATOR_copy] set [Field1] = replace([Field1], '.', ','); and etc

EXEC sp_executesql @sql