跨多个SQL Server数据库比较表名

xxslljrj  于 2022-09-18  发布在  Java
关注(0)|答案(2)|浏览(170)

我正在尝试运行一个SQL Server导出,它会比较一个SQL Server示例上的三个或更多数据库中列出的表名(实际上这个数字要高得多!)

我可以使用如下所示的简单内容来获取特定数据库中所有表的列表。

SELECT [name] 
FROM DB1.sys.tables

我希望能够做的是能够连接这些为多个数据库,以创建一个单一的视图,以发现差异(和相似之处)。

例如,如果我有三个数据库,其中包含以下表

DB1:

Customers
Orders
Products

DB2.

Products
Orders

DB3:

Products
Suppliers

我如何才能将它们结合在一起来获得类似以下的东西?

DB1|DB2|DB3
-|-|
Customers|空|空
Orders|Orders|空
产品|产品|产品
空|空|供应商

谢谢!

ecbunoof

ecbunoof1#

使用公共表表达式获取信息架构表中的表名,并使用完全外连接来实现此目的。

;with tables_in_DB1 as
(
select * from DB1.INFORMATION_SCHEMA.TABLES
where TABLE_TYPE='BASE TABLE'
), 
tables_in_DB2 as
(
select * from DB2.INFORMATION_SCHEMA.TABLES
where TABLE_TYPE='BASE TABLE'
), 
tables_in_DB3 as
(
select * from DB3.INFORMATION_SCHEMA.TABLES
where TABLE_TYPE='BASE TABLE'
) 

select db1.table_name as DB2,db2.table_name as DB2,
db3.table_name as DB3 from tables_in_DB1 db1 
full outer join tables_in_DB2 db2 on db1.TABLE_NAME=db2.TABLE_NAME 
full outer join tables_in_DB3 db3 on db2.TABLE_NAME=db3.TABLE_NAME
omhiaaxx

omhiaaxx2#

这个脚本应该会提供您正在寻找的内容,并且可以通过修改第20行周围的WHERE子句轻松地进行扩展

--Set up some global temporary tables
CREATE TABLE ##all_tables(
    [database_name] sysname,
    [table_name] sysname
)

CREATE TABLE ##tables_for_relevant_dbs(
    [database_name] sysname,
    [table_name] sysname
)

--Capture a list of all the tables in all of the databases on the instance
exec sp_MSforeachdb 'insert into ##all_tables select ''?'', [name] from [?].sys.tables'

--Filter to get the tables from the relevant databases
INSERT INTO ##tables_for_relevant_dbs 
    SELECT dbs.[database_name],tbls.[table_name]
    FROM (select distinct database_name from ##all_tables) dbs
    LEFT JOIN ##all_tables tbls on tbls.database_name=dbs.database_name
    WHERE dbs.database_name like '%' --PUT SOMETHING ELSE HERE

--This magic TSQL concatenates a column of values into a single string
--This string is then used in the dynamic pivoting below
DECLARE @dblist VARCHAR(MAX)

SELECT 
@dblist = STUFF((SELECT ', [' + d_name + ']' AS [text()]
FROM (SELECT DISTINCT 
database_name d_name 
FROM ##tables_for_relevant_dbs) d 
ORDER BY d_name
FOR XML PATH('')), 1, 1, '')

--Pivot the data to turn the database names into columns
EXEC ('SELECT ' + @dblist + '
FROM (SELECT at1.database_name, at2.table_name src, at1.table_name dest
FROM ##tables_for_relevant_dbs at1
LEFT JOIN ##tables_for_relevant_dbs at2 on at2.database_name=at1.database_name and at2.table_name=at1.table_name) t
PIVOT (max(t.src) FOR [database_name] IN (' + @dblist + ')) as [PVT]')

--Clean up
DROP TABLE ##all_tables
DROP TABLE ##tables_for_relevant_dbs

相关问题