所以我有两个环境Test and Prod。
我在两种环境中都有相同的表格。两个表都有很多列。
如何检查一个表中是否有任何列不在另一个表中,而不单独比较它们?对此有任何技巧或提示吗?
我试过
SELECT t.name as table_name,
SCHEMA_NAME(schema_ID) as schema_name,
c.name as column_name
from sys.tables as t
inner join sys.columns c on t.object_ID = c.object_ID
WHERE t.name like '834daily%'
但它没有返回任何东西。
两个SQL数据库都在不同的服务器上,.100
是测试版,.110
是prod。
我确信在SQL中有一种简单的方法可以做到这一点,但不确定最好的方法。我也做了一些事情,比如写出CREATE TABLE
声明,但我永远不能让它们并排进行直接比较。这可能吗?
答案 0 :(得分:0)
你可能会这样做:
LINKED SERVER:
--find your both test and prod server name by running query below
select * from sys.servers
--query to find column name that exists in one environment and not in other
--replace SERVERNAME AND DATABASENAME as needed
SELECT COLUMN_NAME
FROM SERVERNAME.DATABASENAME.INFORMATION_SCHEMA.COLUMNS prod
WHERE TABLE_NAME = 'YourTableName'
AND NOT EXISTS (
SELECT 1
FROM SERVERNAME.DATABASENAME.INFORMATION_SCHEMA.COLUMNS test
WHERE prod.TABLE_NAME = test.TABLE_NAME);
非连接服务器:
--replace SERVERNAME AND DATABASENAME to match yours
SELECT COLUMN_NAME
FROM (
SELECT COLUMN_NAME
,TABLE_NAME
FROM OPENROWSET('SQLNCLI', 'Server=SERVERNAME;Trusted_Connection=yes;',
'SELECT COLUMN_NAME,TABLE_NAME FROM DATABASENAME.INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = ''YOURTABLENAME''')
) AS prod
WHERE NOT EXISTS (
SELECT 1
FROM SERVERNAME.DATABASENAME.INFORMATION_SCHEMA.COLUMNS test
WHERE prod.TABLE_NAME = test.TABLE_NAME
);