比较数据库之间的主键约束

时间:2013-10-17 15:54:10

标签: sql sql-server sql-server-2008

下面的查询比较了两个数据库之间的主键。它标识一个数据库中的所有主键约束,但不标识另一个数据库。当我运行查询时,一些约束名称似乎是系统生成的(即PK__afm_scmpref__2D27B809PK__projfund__E34271EE251CF998)因为这些是系统生成的,所以我无法在数据库中对它们进行比较。有没有解决这个问题的方法?

非常感谢,

这是我的代码:

SELECT src.table_name AS src_table,
   src.constraint_name AS scr_constraint_name,
   src.column_name AS src_column_name,
   src.ordinal_position AS src_ordinal_position,
   tgt.table_name AS tgt_table_name ,
   tgt.constraint_name AS tgt_constraint_name,
   tgt.column_name AS tgt_column_name,
   tgt.ordinal_position AS tgt_ordinal_position
from db_comp_src_primary_keys src
   FULL OUTER JOIN
db_comp_tgt_primary_keys tgt ON
    src.table_name = tgt.table_name
    AND src.constraint_name = tgt.constraint_name

 WHERE (   (src.constraint_name IS NULL AND tgt.constraint_name IS NOT NULL)
    OR (src.constraint_name IS NOT NULL AND tgt.constraint_name IS NULL))
 AND (   (           tgt.table_name IS NULL
            AND src.table_name IS NOT NULL
            AND src.constraint_name IS NOT NULL
            AND src.table_name IN
                   (SELECT table_name
                      FROM [HQ-193-STOCK-DBO].INFORMATION_SCHEMA.tables))
        OR (    src.table_name IS NULL
            AND tgt.table_name IS NOT NULL
            AND tgt.constraint_name IS NOT NULL
            AND tgt.table_name IN
                   (SELECT table_name
                      FROM [HQ-211-STOCK-DBO].INFORMATION_SCHEMA.tables)))

1 个答案:

答案 0 :(得分:0)

这样的事情如何检查一个主键的所有列是否与另一个主键相同

SELECT DISTINCT
    QUOTENAME(t1.CONSTRAINT_CATALOG) + '.' + QUOTENAME(t1.CONSTRAINT_SCHEMA) + '.' + QUOTENAME(t1.CONSTRAINT_NAME) [Source],
    QUOTENAME(t2.CONSTRAINT_CATALOG) + '.' + QUOTENAME(t2.CONSTRAINT_SCHEMA) + '.' + QUOTENAME(t2.CONSTRAINT_NAME) [Target],
    CASE WHEN t1.CONSTRAINT_NAME  IS NULL OR t2.CONSTRAINT_NAME IS NULL THEN 'DISCREPANCY'
         WHEN t1.CONSTRAINT_NAME <> t2.CONSTRAINT_NAME THEN 'NAME MISMATCH'
         ELSE 'COMPLETE MATCH' END [Status]
FROM (
    SELECT c.* 
    FROM msdb.INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
    JOIN msdb.INFORMATION_SCHEMA.KEY_COLUMN_USAGE C
      ON C.TABLE_NAME = PK.TABLE_NAME
     AND C.CONSTRAINT_NAME = PK.CONSTRAINT_NAME
    WHERE PK.CONSTRAINT_TYPE = 'PRIMARY KEY'
) t1
FULL JOIN (
    SELECT c.* 
    FROM msdb.INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
    JOIN msdb.INFORMATION_SCHEMA.KEY_COLUMN_USAGE C
      ON C.TABLE_NAME = PK.TABLE_NAME
     AND C.CONSTRAINT_NAME = PK.CONSTRAINT_NAME
    WHERE PK.CONSTRAINT_TYPE = 'PRIMARY KEY'
) t2 ON t2.TABLE_NAME = t1.TABLE_NAME
    AND t2.COLUMN_NAME = t1.COLUMN_NAME