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

时间:2012-04-16 15:40:23

标签: sql-server

我正在尝试查询SQL Server实例,以便为我提供包含特定名称表的数据库列表。这就是我到目前为止......

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

但是我收到以下错误消息

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'.

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

5 个答案:

答案 0 :(得分:3)

不,您不能在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;

答案 1 :(得分:2)

Powershell就是为此而建的:

$server = new-object Microsoft.SqlServer.Management.Smo.Server ".";
foreach ($db in $server.Databases) {
   $t = $db.Tables | where {$_.Schema -eq 'YourSchema' -and $_.Name -eq 'TableName'};
   if ($t -ne $null) {
      $db.Name;
   }
}

答案 2 :(得分:1)

此SQL语句将为您提供包含您要查找的表的所有数据库名称:

EXEC sp_MSForEachDB 'USE [?]; select ''?'' from information_schema.tables where table_name = ''TheTableName''' ;

答案 3 :(得分:0)

您必须使用临时表从exec获取信息。

试试这个

Create Table #TableLocations(DatabaseName varchar(255) not null)
Declare @databaseName VarChar(255)
Declare @QueryString VarChar(255)
Declare DatabaseNameCursor Cursor For Select [Name] From sys.databases
Declare @TableName VarChar(255)
Select @TableName = 'Put your table name here'
Open DatabaseNameCursor
Fetch Next From DatabaseNameCursor Into @databaseName
While @@Fetch_Status = 0
Begin
  Select @QueryString = 'Use ' + @databaseName + ' Insert into #TableLocations Select ''' + @databaseName + ''' From information_schema.tables Where Table_Name = ''' + @TableName + ''''
  Exec(@QueryString)
  Fetch Next From DatabaseNameCursor Into @databaseName 
End
Close DatabaseNameCursor
DeAllocate DataBaseNameCursor
Select * from #TableLocations
Drop Table #TableLocations

答案 4 :(得分:0)

您还可以将存储过程的结果存储在临时表中,然后将其添加到WHERE子句