我的目标是编写一个SQL Server脚本(如果重要,则为2008 R2),它会使列名称包含“限定符”的所有表中的所有值都为空。
E.g。表A包含名为“TemperatureQualifiers”和“SalinityQualifiers”的列。对于该表中的所有行,应将这些值设置为null。还有其他几个表具有相似名称的列。
答案 0 :(得分:4)
这将为您生成更新语句。您可以扩展它以将它们作为动态SQL执行,或者只是将结果剪切/粘贴到另一个SSMS查询窗口并运行它们。
select 'update [' + s.name + '].[' + t.name + '] set [' + c.name + '] = NULL'
from sys.columns c
inner join sys.tables t
on c.object_id = t.object_id
inner join sys.schemas s
on t.schema_id = s.schema_id
where c.name like '%Qualifiers%'
and t.type = 'U'
答案 1 :(得分:2)
这一点迟到了。这将生成一个脚本,该脚本整合了更新,其中同一个表中有多个列需要更新。
DECLARE @Script nvarchar(MAX);
SET @Script = '';
WITH Cols AS
( SELECT c.object_id,
c.name,
schema_name(t.schema_id) AS SchemaName,
t.name AS TableName
FROM sys.columns c INNER JOIN
sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE '%Qualifiers%'
AND is_computed=0
AND is_rowguidcol=0
AND is_identity=0
AND is_nullable=1
AND objectproperty(c.object_id, N'IsUserTable')=1
)
,
Tables AS
( SELECT DISTINCT object_id, TableName, SchemaName
FROM Cols
)
,
Statements AS
( SELECT 'UPDATE ' + QUOTENAME(SchemaName) + '.' + QUOTENAME(TableName) + ' SET ' + STUFF(
( SELECT ',' + c.name + '=NULL'
FROM Cols c
WHERE c.object_id = t.object_id FOR XML PATH('')
)
, 1, 1, '') AS Statement
FROM Tables t
)
SELECT @Script = @Script + '
' +Statement
FROM Statements
SELECT @Script AS [processing-instruction(x)] FOR XML PATH('')