INFORMATION_SCHEMA.COLUMNS限制搜索到表

时间:2014-01-09 16:47:11

标签: sql sql-server-2008

我有一个查询,查看两个数据库中的INFORMATION_SCHEMA.COLUMNS视图。它查看数据库中的每一列,并将属性与另一个数据库中的同一列(实际上是table.column)进行比较。

代码工作正常,但是当我运行INFORMATION_SCHEMA.COLUMNS时,它会获取表和视图中存在的列的定义。我需要限制查询只查看表。

有人可以建议我怎么做吗?

这是我的代码:

SELECT 
      CASE
         WHEN src.TABLE_NAME IS NULL AND src.COLUMN_NAME IS NULL
         THEN
            tgt.TABLE_NAME + '.' + tgt.COLUMN_NAME
         ELSE
            src.TABLE_NAME + '.' + src.COLUMN_NAME
      END
         AS object_name,
FROM [hq193].INFORMATION_SCHEMA.COLUMNS src
      FULL JOIN [GDI-193-DEV].INFORMATION_SCHEMA.COLUMNS tgt
         ON     src.table_name = tgt.table_name
            AND src.COLUMN_NAME = tgt.COLUMN_NAME
WHERE    src.CHARACTER_MAXIMUM_LENGTH != tgt.CHARACTER_MAXIMUM_LENGTH
      OR src.DATA_TYPE != tgt.DATA_TYPE
      OR src.IS_NULLABLE != tgt.IS_NULLABLE
      OR src.NUMERIC_PRECISION != tgt.NUMERIC_PRECISION
      OR src.NUMERIC_SCALE != tgt.NUMERIC_SCALE

提前致谢,

1 个答案:

答案 0 :(得分:1)

而不是INFORMATION_SCHEMA我更喜欢使用sys.tablessys.columnsJOIN object_id上的SELECT * FROM sys.columns c JOIN sys.tables t ON c.object_id = t.object_id

sys.views

有关观看的信息包含在;WITH db1 AS ( SELECT c.*,t.name Table_Name FROM sys.columns c JOIN sys.tables t ON c.object_id = t.OBJECT_ID ) ,db2 AS ( SELECT c.*,t.name Table_Name FROM db2.sys.columns c JOIN db2.sys.tables t ON c.object_id = t.OBJECT_ID ) SELECT CASE WHEN db1.Table_Name IS NULL AND db1.name IS NULL THEN db2.Table_Name + '.' + db2.name ELSE db1.Table_Name + '.' + db1.name END AS object_name FROM db1 FULL JOIN db2 ON db1.Table_Name = db2.Table_Name AND db1.name = db2.name WHERE db1.max_length <> db2.max_length OR db1.system_type_id <> db2.system_type_id OR db1.is_nullable <> db2.is_nullable OR db1.precision <> db2.precision OR db1.scale <> db2.scale

类似的东西:

JOIN

或者您可以向当前查询添加sys.tablesSELECT CASE WHEN src.TABLE_NAME IS NULL AND src.COLUMN_NAME IS NULL THEN tgt.TABLE_NAME + '.' + tgt.COLUMN_NAME ELSE src.TABLE_NAME + '.' + src.COLUMN_NAME END AS object_name, FROM [hq193].INFORMATION_SCHEMA.COLUMNS src JOIN [hq193].sys.tables t ON src.table_name = t.name FULL JOIN [GDI-193-DEV].INFORMATION_SCHEMA.COLUMNS tgt ON src.table_name = tgt.table_name AND src.COLUMN_NAME = tgt.COLUMN_NAME WHERE src.CHARACTER_MAXIMUM_LENGTH != tgt.CHARACTER_MAXIMUM_LENGTH OR src.DATA_TYPE != tgt.DATA_TYPE OR src.IS_NULLABLE != tgt.IS_NULLABLE OR src.NUMERIC_PRECISION != tgt.NUMERIC_PRECISION OR src.NUMERIC_SCALE != tgt.NUMERIC_SCALE 以清除视图:

JOIN

可能需要切换sys.tables {{1}}所在的db。