确保外键的两侧是相同列类型的最佳方法

时间:2014-07-07 10:52:59

标签: sql sql-server-2008-r2

我有一个大型数据库,我们正在进入一个项目,将int标识字段更改为BigInt或GUID。

我已经改变了一些,但现在我想看看是否所有的外键都改变了对方。

是的,我可以通过它们,但我希望找到一种可以比较双方的某种脚本,并在列类型不匹配时提醒我?

1 个答案:

答案 0 :(得分:0)

我通过屠杀别人的代码来解决这个问题。

SELECT C.TABLE_CATALOG [PKTABLE_QUALIFIER], 
   C.TABLE_SCHEMA [PKTABLE_OWNER], 
   C.TABLE_NAME [PKTABLE_NAME], 
   KCU.COLUMN_NAME [PKCOLUMN_NAME], 
   col.Data_Type,
   C2.TABLE_CATALOG [FKTABLE_QUALIFIER], 
   C2.TABLE_SCHEMA [FKTABLE_OWNER], 
   C2.TABLE_NAME [FKTABLE_NAME], 
   KCU2.COLUMN_NAME [FKCOLUMN_NAME], 
   RC.UPDATE_RULE, 
   RC.DELETE_RULE, 
   C.CONSTRAINT_NAME [FK_NAME], 
   C2.CONSTRAINT_NAME [PK_NAME], 
   CAST(7 AS SMALLINT) [DEFERRABILITY] 
FROM   INFORMATION_SCHEMA.TABLE_CONSTRAINTS C 
   INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU 
     ON C.CONSTRAINT_SCHEMA = KCU.CONSTRAINT_SCHEMA 
        AND C.CONSTRAINT_NAME = KCU.CONSTRAINT_NAME 
   INNER JOIN INFORMATION_SCHEMA.COLUMNS col
     ON col.Table_Name =  C.TABLE_NAME
     AND col.Column_Name = KCU.COLUMN_NAME
   INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC 
     ON C.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA 
        AND C.CONSTRAINT_NAME = RC.CONSTRAINT_NAME 
   INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS C2 
     ON RC.UNIQUE_CONSTRAINT_SCHEMA = C2.CONSTRAINT_SCHEMA 
        AND RC.UNIQUE_CONSTRAINT_NAME = C2.CONSTRAINT_NAME 
   INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU2 
     ON C2.CONSTRAINT_SCHEMA = KCU2.CONSTRAINT_SCHEMA 
        AND C2.CONSTRAINT_NAME = KCU2.CONSTRAINT_NAME 
        AND KCU.ORDINAL_POSITION = KCU2.ORDINAL_POSITION 
   INNER JOIN INFORMATION_SCHEMA.COLUMNS col2
     ON col2.Table_Name =  C2.TABLE_NAME
     AND col2.Column_Name = KCU2.COLUMN_NAME

WHERE  C.CONSTRAINT_TYPE = 'FOREIGN KEY'
AND col.Data_Type <> col2.Data_Type