Question

Pinal Dave has this neat query where he finds all the columns named EmployeeID across all the tables in his database:

select t.name as table_name,
    schema_name(schema_id) as schema_name,
    c.name as column_name
from sys.tables as t
inner join sys.columns c on t.object_id = c.object_id
where c.name like '%EmployeeID%'
order by schema_name, table_name;

Is there a way to join that data to the data in the matched columns?

I've tried adding an additional join and looking through the other sys.* items to see if one of them sounded like it might be the data.

I have also tried constructing an outer select around this one, but that requires the joins to be in a format that (clearly) doesn't work:

select ( /* above */ ) as foo
inner join foo.table_name bar on bar.something = foo.something --???

Is there something else I can be doing? My ultimate aim is to update EmployeeID for all of the rows in all of the tables.

Was it helpful?

Solution

As mentioned, this can't be done as you are imagining, as data is stored in tables, and the catalog views (sys.) contain information about database objects.

You can achieve what you're after with a cursor and dynamic sql:

DECLARE @col VARCHAR(MAX)
       ,@table VARCHAR(MAX)
       ,@schema VARCHAR(MAX)
       ,@strSQL VARCHAR(MAX)
DECLARE xyz CURSOR
FOR
        SELECT c.name
              ,t.name
              ,s.name
        FROM sys.tables t
        JOIN sys.columns c
         ON t.object_ID = c.object_ID
        JOIN sys.schemas s
         ON t.schema_id = s.schema_id
        WHERE c.name LIKE '%EmployeeID%';    
OPEN xyz 
FETCH NEXT FROM xyz 
INTO @col,@table,@schema 
WHILE @@FETCH_STATUS = 0
BEGIN

SET @strSQL = 
'UPDATE '+@schema+'.'+@table+' 
 SET '+@col+' = ''Something''
'
PRINT (@strSQL)

    FETCH NEXT FROM xyz 
    INTO @col,@table,@schema 
END
CLOSE xyz 
DEALLOCATE xyz 
GO

It's a good idea to test dynamic sql with the PRINT command before actually running it via EXEC.

OTHER TIPS

No, you can't in the way you seem to want.

Try writing code that generates T-SQL in something like LINQPad. Or write code that generates dynamic SQL in T-SQL itself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top