如何将所有数据库名称和相应的表名一起获取?
答案 0 :(得分:1)
CREATE TABLE #dbs ( DatabaseName VARCHAR(256), TableName VARCHAR(256) )
EXEC sp_msforeachdb 'INSERT INTO #dbs
SELECT ''?'', [name] FROM dbo.SysObjects WHERE XType = ''U'''
SELECT * FROM #dbs
DROP TABLE #dbs
答案 1 :(得分:0)
您必须编写商店程序。
首先获取数据库名称
SELECT Name FROM master.sys.databases
对于每个数据库
SELECT %DatabaseName%, Name FROM %DatabaseName%.SysObjects WHERE type = 'U'
在这里编辑商店程序
CREATE PROCEDURE sp_GetDatabasesTables
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
CREATE TABLE #schema ( DatabaseName VarChar(50), TableName VarChar(50) );
DECLARE @DatabaseName varchar(50);
DECLARE cursorDatabase CURSOR FOR
SELECT Name FROM master.sys.databases WHERE Name NOT IN ('tempdb'); -- add any table you want to filter here
OPEN cursorDatabase;
-- Perform the first fetch.
FETCH NEXT FROM cursorDatabase INTO @DatabaseName;
-- Check @@FETCH_STATUS to see if there are any more rows to fetch.
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC ('INSERT INTO #schema (DatabaseName, TableName) SELECT ''' + @DatabaseName + ''' AS DatabaseName, Name As TableName FROM ' + @DatabaseName + '.sys.SysObjects WHERE type = ''U'';');
FETCH NEXT FROM cursorDatabase INTO @DatabaseName;
END
CLOSE cursorDatabase;
DEALLOCATE cursorDatabase;
SELECT * FROM #schema
END