6

我正在尝试查询 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'.

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

4

5 回答 5

4

不,您不能execwhere子句中使用。一些动态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;
于 2012-04-16T15:51:08.557 回答
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;
   }
}
于 2012-04-16T22:08:11.850 回答
1

This SQL statement will give you all of the database names that contain the table you are looking for:

EXEC sp_MSForEachDB 'USE [?]; select ''?'' from information_schema.tables where table_name = ''TheTableName''' ;
于 2012-04-16T15:53:11.473 回答
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
于 2012-04-16T16:02:12.697 回答
0

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

于 2013-02-08T14:39:07.117 回答