此SQL查询打印表名,列名和列类型(Data,varchar等)。
Table_name Column_name Data_type
SELECT T.TABLE_NAME,C.COLUMN_NAME,C.DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS C
INNER JOIN INFORMATION_SCHEMA.TABLES T ON C.TABLE_NAME = T.TABLE_NAME
AND C.TABLE_SCHEMA = T.TABLE_SCHEMA
WHERE T.TABLE_TYPE = 'BASE TABLE'
如果这个列是复合主键的一部分(见下文),如何更改它以便打印?
Table_name Column_Name Is_Primary(y / n)Data_Type
更新:建议的副本相差甚远,因为它涉及单个表。接受的答案解决了我的问题。
答案 0 :(得分:1)
约束名称和类型位于INFORMATION_SCHEMA.TABLE_CONSTRAINTS
中,列名称和约束名称位于INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE
中。所以,基本上你最终会添加更多JOINS。
SELECT
T.TABLE_NAME,
C.COLUMN_NAME,
C.DATA_TYPE,
CCU.Constraint_Name,
CASE TC.Constraint_Type
WHEN 'PRIMARY KEY' THEN 'Yes'
ELSE 'No'
END IsPrimaryKey
FROM INFORMATION_SCHEMA.COLUMNS C
INNER JOIN INFORMATION_SCHEMA.TABLES T
ON C.TABLE_NAME = T.TABLE_NAME
AND C.TABLE_SCHEMA = T.TABLE_SCHEMA
LEFT JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE CCU
ON CCU.TABLE_SCHEMA = T.TABLE_SCHEMA
AND CCU.TABLE_NAME = T.TABLE_NAME
AND CCU.COLUMN_NAME = C.COLUMN_NAME
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
ON CCU.Constraint_Name = TC.Constraint_Name
AND CCU.Table_Name = TC.Table_Name
AND CCU.TABLE_SCHEMA = TC.TABLE_SCHEMA
WHERE T.TABLE_TYPE = 'BASE TABLE'
ORDER BY T.TABLE_NAME, C.COLUMN_NAME