有没有办法在where子句中使用`exec`?

Nic*_*pat 6 sql-server

我试图查询SQL Server的一个实例,给我一个包含特定名称表的数据库列表.这就是我到目前为止......

select name
from master..sysdatabases
where (exec('use ' + name + '; select 1 from information_schema.tables 
  where table_name = ''TheTableName'';')) = 1;
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误消息

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'.
Run Code Online (Sandbox Code Playgroud)

exec()在where子句中使用call的正确语法是什么?或者还有另一种方法可以做我想做的事情吗?

Aar*_*and 4

exec不,您不能在子句中使用where。一些动态 SQL 怎么样:

DECLARE @sql NVARCHAR(MAX);

SET @sql = N'SELECT name = NULL WHERE 1 = 0';

SELECT @sql = @sql + N'
  UNION ALL SELECT name = ''' + name + ''' 
  WHERE EXISTS (SELECT 1 FROM ' + QUOTENAME(name)
  + '.sys.tables WHERE name = ''TheTableName'')'
  FROM sys.databases;

EXEC sp_executesql @sql;
Run Code Online (Sandbox Code Playgroud)