我的应用程序有一个旧的SQL 2008备份。今天我们遇到了一个案例,我们希望将它恢复为sql-2012中的当前数据库。我使用以下查询来计算两个数据库中的表
USE YOURDBNAME
SELECT COUNT(*) from information_schema.tables
WHERE table_type = 'base table'
我当前的数据库返回总计543个表而旧数据库 显示533张表
如何通过将当前数据库中的唯一十个表与我以前的数据库表进行比较来查找它们。 ?
更新1
我使用下面的查询比较表但没有返回结果
select 'dbtest01' as dbname, t1.table_name
from dbtest01.[INFORMATION_SCHEMA].[tables] t1
where table_name not in (select t2.table_name
from
dbtest02.[INFORMATION_SCHEMA].[tables] t2
)
union
select 'dbtest02' as dbname, t1.table_name
from dbtest02.[INFORMATION_SCHEMA].[tables] t1
where table_name not in (select t2.table_name
from
dbtest01.[INFORMATION_SCHEMA].[tables] t2
)
答案 0 :(得分:3)
此查询包含table_schema,以确保表名是否重复但在不同的模式中显示。这将显示db_1中但不在db_2中的表以及db_2中的表但不在db_1中。
SELECT
db1.dbname AS db1_name,
db1.table_schema AS db1_schema,
db1.table_name AS db1_table,
db2.dbname AS db2_name,
db2.table_schema AS db2_schema,
db2.table_name AS db2_table
FROM (
SELECT
'YOURDBNAME' AS dbname,
table_schema,
table_name
FROM YOURDBNAME.information_schema.tables
WHERE table_type = 'BASE TABLE'
) AS db1
FULL OUTER JOIN (
SELECT
'YOUROTHERDBNAME' AS dbname,
table_schema,
table_name
FROM YOUROTHERDBNAME.information_schema.tables
WHERE table_type = 'BASE TABLE'
) AS db2 ON
db1.table_schema = db2.table_schema
AND db1.table_name = db2.table_name
WHERE db1.dbname IS NULL
OR db2.dbname IS NULL
答案 1 :(得分:2)
这两个查询将作为一个快速的即席查询来完成工作。你必须在“两个方向”做两次,以捕捉所有可能的差异。
-- All tables in dbtest01 that are not in dbtest02
SELECT schema_name(schema_id), name
from dbtest01.sys.tables
except select schema_name(schema_id), name
from dbtest02.sys.tables
order by name
-- All tables in dbtest02 that are not in dbtest01
SELECT schema_name(schema_id), name
from dbtest01.sys.tables
except select schema_name(schema_id), name
from dbtest02.sys.tables
order by name
(根据@Andrew的回复更新了架构。完整的外部联接也起作用,但它们伤害了我的大脑。)
答案 2 :(得分:1)
SELECT table_name from dbtest01.information_schema.tables
WHERE table_type = 'base table'
EXCEPT
SELECT table_name from dbtest02.information_schema.tables
WHERE table_type = 'base table'