tags:

views:

34

answers:

2

My goal is to write a SQL Server script (2008 R2 if it matters) that nulls out all values in all tables where the column name contains "Qualifiers".

E.g. Table A contains columns named "TemperatureQualifiers" and "SalinityQualifiers". For all rows in that table, those values should be set to null. There are also several other tables that have columns with similar names.

+4  A: 

This will generate the update statements for you. You can extend this to execute them as dynamic SQL or simply cut/paste the results to another SSMS query window and run them.

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'
Joe Stefanelli
Exec(@SQL) this will execute the dynamic sql.
Vash
Awesome! Exactly what I was looking for.
KevDog
quote those names for extra zing.
Peter
@Peter: Extra zing added. :-)
Joe Stefanelli
`CREATE TABLE [[With Spiteful]]] ([[Identifiers]]] INT, []]^!^[] CHAR(10))`
Peter
@Peter: I get your point, but in that case, I'd rather have my script fail so I could identify and strangle the developer who came up with those object names! :-)
Joe Stefanelli
+2  A: 

Bit late on this one. This will generate a script that consolidates updates where there are multiple columns in the same table to be updated.

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('')
Martin Smith