我正在使用以下查询来获取所需表的约束:
SELECT
OBJECT_NAME(o.object_id) AS ConstraintName,
SCHEMA_NAME(schema_id) AS SchemaName,
OBJECT_NAME(parent_object_id) AS TableName,
type_desc AS ConstraintType
FROM
sys.objects o
-- INNER JOIN
-- sys.columns c ON o.object_id = c.object_id
WHERE
type_desc LIKE '%CONSTRAINT'
AND OBJECT_NAME(parent_object_id)= 'All_Data_Types'
成功获取表格约束详细信息。但是,我也需要专栏的信息。
有人可以帮我吗?
预先感谢
答案 0 :(得分:2)
默认约束的快速解决方案是
SELECT dc.object_id AS ConstraintID, DC.name AS ConstraintName
, O.object_id AS TableID, O.name AS TableName
, C.object_id AS ColumnID, C.name AS ColName
FROM sys.default_constraints AS DC
LEFT JOIN sys.objects AS O ON O.object_id = DC.parent_object_id
LEFT JOIN sys.columns c ON o.object_id = c.object_id AND DC.parent_column_id = c.column_id
答案 1 :(得分:2)
对于表约束,您可以使用类似以下的内容:
SELECT KCU.*, TC.CONSTRAINT_TYPE
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC ON TC.CONSTRAINT_SCHEMA = KCU.CONSTRAINT_SCHEMA AND TC.CONSTRAINT_NAME = KCU.CONSTRAINT_NAME
答案 2 :(得分:2)
如果您使用的是SQL Server 2012或更高版本,则可以使用系统视图sys.sysconstraints
:
包含约束到拥有该对象的对象的映射 数据库中的约束。
因此,此查询:
SELECT *
FROM sys.sysconstraints s
INNER JOIN sys.objects o ON o.object_id = s.constid
理论上,返回与查询相同的行数。但是,现在您有了有关在其上定义约束的列的ID的其他信息。那就是sys.sysconstraints
的colid
列:
定义约束的列的ID。
0 =表约束
因此,使用此查询:
SELECT OBJECT_NAME(o.object_id) AS ConstraintName,
SCHEMA_NAME(o.schema_id) AS SchemaName,
OBJECT_NAME(o.parent_object_id) AS TableName,
o.type_desc AS ConstraintType,
COALESCE(c.COLUMN_NAME, 'Table constraint') AS ColumnName
FROM sys.sysconstraints s
INNER JOIN sys.objects o ON o.object_id = s.constid
LEFT JOIN INFORMATION_SCHEMA.COLUMNS c ON c.ORDINAL_POSITION = s.colid AND s.colid <> 0
您还将获得与约束相关的列的名称。
答案 3 :(得分:1)
这是查询。您在错误的表column_name上使用static Ad Select(this IReadOnlyList<Ad> ads)
{
var range = ads.ToRange().ToList();
int selectedIndex = rnd.Next(range.Count);
return ads[selectedIndex];
}
static IEnumerable<Ad> SelectAds(this IEnumerable<Ad> ads, int selectCount)
{
for (int i=0; i<selectCount; ++i)
{
var selectedAd = ads.Select();
yield return selectedAd;
selectedAd.IsDisplayed = true; // to make sure it is not selected again
}
}
。
您使用了
INNER JOIN
我将其替换为
INNER JOIN sys.columns c ON o.object_id = c.object_id
现在,您可以看到column_name和table_name以及constraint_details。
INNER JOIN sys.columns c ON o.parent_object_id = c.object_id
也请避免使用以下子句
SELECT OBJECT_NAME(o.object_id) AS ConstraintName,
SCHEMA_NAME(schema_id) AS SchemaName,
OBJECT_NAME(parent_object_id) AS TableName,
c.name as ColumnName,
type_desc AS ConstraintType
FROM sys.objects o
INNER JOIN sys.columns c ON o.parent_object_id = c.object_id
WHERE type_desc LIKE '%CONSTRAINT';