我在服务器中有10个数据库,是否可以在所有这些数据库中查询表?
select * from master..sysobjects where name ='table'
答案 0 :(得分:0)
您可以使用以下SQL获取每个数据库的所有表。如果您愿意,可以编辑@SQL参数中的SQL以获取每个数据库的其他内容
DECLARE @databaseName VARCHAR(30)
DECLARE @TABLES TABLE ([Database] VARCHAR(MAX), [Table_Name] VARCHAR(MAX))
DECLARE [DBs] CURSOR FOR
SELECT name FROM sys.databases
OPEN [DBs]
FETCH NEXT FROM [DBs] INTO @databaseName
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @SQL VARCHAR(MAX) = 'SELECT ''' + @databaseName +''' as [Database], Name FROM ['+ @databaseName +'].sys.tables'
INSERT INTO @TABLES
EXEC (@SQL)
FETCH NEXT FROM [DBs] INTO @databaseName
END
CLOSE [DBs]
DEALLOCATE [DBs]
SELECT * FROM @TABLES
答案 1 :(得分:0)
您可以使用以下步骤。
Declare @str nvarchar(max)
Select name into #temp from sys.databases
Select 'Select name from '+name+'.sys.tables' AS statements into #temp1 from #temp
Set @str=(Select distinct Stuff((Select ' '+statements from #temp1 for xml path('')),1,1,'') from #temp1)
Exec (@str)