我认为这非常简单,但我在服务器中有大约80个数据库,每个数据库有5-500个表。
我想知道如何在所有内容中搜索TABLE NAME。我尝试了一个基本的
SELECT
*
FROM sys.tables
但我只得到6个结果。
答案 0 :(得分:2)
这有点像黑客,但我认为它应该有效:
sp_msforeachdb 'select ''?'' from ?.information_schema.tables where table_name=''YourTableName''';
它将输出包含具有给定名称的表的DB的名称。
这是使用print
的版本,这是一个更好的恕我直言:
sp_msforeachdb '
if exists(select * from ?.information_schema.tables where table_name=''YourTableName'')
print ''?'' ';
上述查询使用ms_foreachdb,这是一个存储过程,对当前服务器上存在的所有数据库运行给定查询。
答案 1 :(得分:1)
仅仅因为我真的不喜欢循环,我想发布一个替代已经发布的使用游标的答案。
这利用了动态sql和sys.databases表。
declare @SQL nvarchar(max) = ''
select @SQL = @SQL + 'select DatabaseName = name from [' + name + '].sys.tables where name = ''YourTableName'' union all '
from sys.databases
set @SQL = stuff(@SQL, len(@SQL) - 9, 11, '') --removes the last UNION ALL
exec sp_executesql @SQL
答案 2 :(得分:1)
此版本使用FOR XML PATH('')而不是字符串连接,消除默认系统数据库,处理具有非标准名称的数据库并支持搜索模式。
DECLARE @pattern NVARCHAR(128) = '%yourpattern%';
DECLARE @sql NVARCHAR(max) = STUFF((
SELECT 'union all select DatabaseName = name from ' + QUOTENAME(d.name) + '.sys.tables where name like ''' + @pattern + ''' '
FROM sys.databases d
WHERE d.database_id > 4
FOR XML path('')
), 1, 10, '');
EXEC sp_executesql @sql;
您可能需要写:
select DatabaseName = name collate Latin1_General_CI_AS
我知道我做到了。
答案 3 :(得分:0)
这是使用动态sql的一个更简单的选项。这将为您提供环境中每个数据库中所有表的名称:
declare @table table (idx int identity, name varchar(max))
insert @table
select name from master.sys.databases
declare @dbname varchar(max)
declare @iterator int=1
while @iterator<=(select max(idx) from @table) begin
select @dbname=name from @table where idx=@iterator
exec('use ['+@dbname+'] select name from sys.tables')
set @iterator=@iterator+1
end
select * from @table
答案 4 :(得分:-1)
Dim sql As String =(“从*&ComboboxDatabaseName.Text和” .sys.tables“中选择*)
使用此键