我目前正在使用...
select Table_Name, Column_name, data_type, is_Nullable
from information_Schema.Columns
...确定有关给定数据库中列的信息,以生成数据访问层。
我可以从哪里检索有关这些列是否是其表主键中的参与者的信息?
我目前正在使用...
select Table_Name, Column_name, data_type, is_Nullable
from information_Schema.Columns
...确定有关给定数据库中列的信息,以生成数据访问层。
我可以从哪里检索有关这些列是否是其表主键中的参与者的信息?
这是一种方法(将“keycol”替换为您要搜索的列名):
SELECT K.TABLE_NAME ,
K.COLUMN_NAME ,
K.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K ON C.TABLE_NAME = K.TABLE_NAME
AND C.CONSTRAINT_CATALOG = K.CONSTRAINT_CATALOG
AND C.CONSTRAINT_SCHEMA = K.CONSTRAINT_SCHEMA
AND C.CONSTRAINT_NAME = K.CONSTRAINT_NAME
WHERE C.CONSTRAINT_TYPE = 'PRIMARY KEY'
AND K.COLUMN_NAME = 'keycol';
同样,以下将为您提供有关所有表及其键的信息,而不是有关特定列的信息。这样,您可以确保您拥有所有感兴趣的列并知道它们参与的内容。为了查看所有键(主键、外键、唯一键),请注释 WHERE 子句。
SELECT K.TABLE_NAME, C.CONSTRAINT_TYPE, K.COLUMN_NAME, K.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K
ON C.TABLE_NAME = K.TABLE_NAME
AND C.CONSTRAINT_CATALOG = K.CONSTRAINT_CATALOG
AND C.CONSTRAINT_SCHEMA = K.CONSTRAINT_SCHEMA
AND C.CONSTRAINT_NAME = K.CONSTRAINT_NAME
WHERE C.CONSTRAINT_TYPE = 'PRIMARY KEY'
ORDER BY K.TABLE_NAME, C.CONSTRAINT_TYPE, K.CONSTRAINT_NAME
根据您的需要,使用 INFORMATION_SCHEMA.COLUMNS 和 INFORMATION_SCHEMA.KEY_COLUMN_USAGE 进行完全外部联接。在 select 语句中,从 INFORMATION_SCHEMA.KEY_COLUMN_USAGE 添加 CONSTRAINT_NAME 列,这将为您提供 null 或键名。
select C.Table_Name, C.Column_name, data_type, is_Nullable, U.CONSTRAINT_NAME
from information_Schema.Columns C FULL OUTER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE U ON C.COLUMN_NAME = U.COLUMN_NAME
WHERE C.TABLE_NAME=@TABLENAME
此查询返回列是主键。
SELECT col.COLUMN_NAME ,
col.DATA_TYPE ,
col.CHARACTER_MAXIMUM_LENGTH ln ,
CAST(ISNULL(j.is_primary, 0) AS BIT) is_primary
FROM INFORMATION_SCHEMA.COLUMNS col
LEFT JOIN ( SELECT K.TABLE_NAME ,
K.COLUMN_NAME ,
CASE WHEN K.CONSTRAINT_NAME IS NULL THEN 0
WHEN K.CONSTRAINT_NAME IS NOT NULL THEN 1
END is_primary
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K ON C.TABLE_NAME = K.TABLE_NAME
AND C.CONSTRAINT_CATALOG = K.CONSTRAINT_CATALOG
AND C.CONSTRAINT_SCHEMA = K.CONSTRAINT_SCHEMA
AND C.CONSTRAINT_NAME = K.CONSTRAINT_NAME
WHERE C.CONSTRAINT_TYPE = 'PRIMARY KEY'
AND C.TABLE_NAME = 'tablename'
) j ON col.COLUMN_NAME = j.COLUMN_NAME
WHERE col.TABLE_NAME = 'tablename'