我编写了一个查询来基于数据库 ( Tracker
) 和表 ( Work
) 查找列元数据:
SELECT Cols.Name,
TYPE_NAME(Cols.user_type_id) Type,
CAST(ISNULL(OBJECTPROPERTY(OBJECT_ID(Keys.CONSTRAINT_NAME), 'IsPrimaryKey'), 0) AS BIT) PrimaryKey,
Cols.is_identity [Identity],
Cols.is_nullable Nullable,
CAST(ColumnProperty(object_id, Cols.name, 'IsComputed') AS BIT) Computed,
CASE WHEN Cons.CONSTRAINT_TYPE IS NULL THEN NULL ELSE Keys.CONSTRAINT_NAME END ForeignKey
FROM sys.columns Cols
LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE Keys
ON Keys.COLUMN_NAME = Cols.name
AND Keys.TABLE_CATALOG = 'Tracker'
AND Keys.TABLE_NAME = 'Work'
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS Cons
ON Cons.CONSTRAINT_NAME = Keys.CONSTRAINT_NAME
AND Cons.CONSTRAINT_TYPE = 'FOREIGN KEY'
WHERE Cols.object_id = OBJECT_ID('Work')
ORDER BY Cols.column_id ASC
这产生了这个结果:
我还编写了这个查询来查找外键的关系信息:
SELECT OBJECT_NAME(FKCols.referenced_object_id) ForeignTable,
Cols.name ForeignColumn
FROM sys.foreign_key_columns FKCols
LEFT JOIN sys.foreign_keys FKs
ON FKCols.constraint_object_id = FKs.object_id
LEFT JOIN sys.columns Cols
ON Cols.object_id = FKs.referenced_object_id
WHERE Cols.column_id = FKCols.referenced_column_id
AND FKs.name = 'FK_Work_Tasks'
产生这个:
我花了几个小时才达到这一点,但我真的被困住了。我试图得到这样的结果:
如何将这些查询合并在一起?
我打算将此发布到DBA,但我不确定这是否属于基本或高级 SQL 查询(离题/离题)的范围。
此外,如果有人能指出我可以在这里使用的任何优化,那也将不胜感激!