I am trying to query an instance of SQL Server to give me a list of databases that contain a table of a specific name. This is what I have so far…
select name
from master..sysdatabases
where (exec('use ' + name + '; select 1 from information_schema.tables
where table_name = ''TheTableName'';')) = 1;
But I get the following error messages
Msg 156, Level 15, State 1, Line 4
Incorrect syntax near the keyword 'exec'.
Msg 102, Level 15, State 1, Line 4
Incorrect syntax near 'name'.
What is the correct syntax to use call exec() in a where clause? Or is there another way to do what I’m trying to do?
No, you cannot use
execin awhereclause. How about some dynamic SQL: