如何获得对 SQL Server 表列的约束

我的表中有一个名为 MealType ( VARCHAR ) 的列,其中 CHECK{"Veg", "NonVeg", "Vegan"} 约束

这将负责插入。

我想显示这些选项以供选择,但我无法找出 SQL 查询来找出表中特定列的约束。

乍一看 SQL Server 中的系统表,我似乎需要使用 SQL Server 的 API 来获取信息。我希望 SQL 查询本身能够得到它。

stack overflow How do I get constraints on a SQL Server table column
原文答案
author avatar

接受的答案

此查询应向您显示表上的所有约束:

select chk.definition
from sys.check_constraints chk
inner join sys.columns col
    on chk.parent_object_id = col.object_id
inner join sys.tables st
    on chk.parent_object_id = st.object_id
where 
st.name = 'Tablename'
and col.column_id = chk.parent_column_id

可以用这个替换select语句:

select substring(chk.Definition,2,3),substring(chk.Definition,9,6),substring(chk.Definition,20,5) 

答案:

作者头像

最简单快捷的方法是使用:

sp_help 'TableName'
作者头像
SELECT obj_table.NAME      AS 'table', 
        columns.NAME        AS 'column',
        obj_Constraint.NAME AS 'constraint',
        obj_Constraint.type AS 'type'

    FROM   sys.objects obj_table 
        JOIN sys.objects obj_Constraint 
            ON obj_table.object_id = obj_Constraint.parent_object_id 
        JOIN sys.sysconstraints constraints 
             ON constraints.constid = obj_Constraint.object_id 
        JOIN sys.columns columns 
             ON columns.object_id = obj_table.object_id 
            AND columns.column_id = constraints.colid 
    WHERE obj_table.NAME='table_name'
    ORDER  BY 'table'
作者头像

您可以使用

sp_helpconstraint 'tableName', 'nomsg'

获取表的所有约束。

“sp_help”返回更多信息。

作者头像

感谢 orgtrigger 的例子!我对其进行了改进,以便能够删除不必要的约束(然后在需要时创建其修改版本)。也许此代码对任何人都有用。

  -- removing old constraints
DECLARE @ConstraintNames TABLE (Name VARCHAR(MAX), RowNum INT)
DECLARE @TableName VARCHAR(100) = 'HubSpot'

INSERT @ConstraintNames
  SELECT [constraint].name,
         ROW_NUMBER() OVER (ORDER BY [constraint].[name]) AS RowNum
  FROM sys.default_constraints [constraint]
  INNER JOIN sys.columns col
      ON [constraint].parent_object_id = col.object_id
  INNER JOIN sys.tables st
      ON [constraint].parent_object_id = st.object_id
  WHERE 
  st.name = @TableName 
  AND col.name IN ('ForceUpdateOnImport', 'ForceUpdateOnExport')
  AND col.column_id = [constraint].parent_column_id

SELECT * FROM @ConstraintNames

DECLARE @i INT = 1,
        @count INT,
        @constraintName VARCHAR(MAX),
        @sql VARCHAR(MAX)
SELECT @count = COUNT(1) FROM @ConstraintNames

WHILE @i <= @count 
  BEGIN 
    SELECT @constraintName = cn.Name FROM @ConstraintNames cn WHERE cn.RowNum = @i
    SET @sql = 'ALTER TABLE ' + @TableName + ' DROP CONSTRAINT ' + @constraintName

    EXEC (@sql)
    SET @i = @i + 1
  END
作者头像

下面有助于检查和默认约束。我将它用于隐式约束,以提供名称应该是什么的指导。如果您删除 where 子句之后的所有内容,它应该适用于任何检查/默认约束。

SELECT /* obj_table.NAME      AS 'table', 
        columns.NAME        AS 'column',
        obj_Constraint.NAME AS 'constraint',
        obj_Constraint.type AS 'type',
        sss.name as 'schema',*/
        'ALTER TABLE [' + ltrim(rtrim(sss.name))+'].['+ltrim(rtrim(obj_table.name)) + '] DROP CONSTRAINT [' + obj_Constraint.NAME + '];' As 'Wrong_Implicit_Constraint',
        'ALTER TABLE [' + ltrim(rtrim(sss.name))+'].['+ltrim(rtrim(obj_table.name)) + '] ADD CONSTRAINT [' + CASE obj_Constraint.type 
        WHEN 'D' THEN 'DF' WHEN 'F' THEN 'FK' 
        WHEN 'U' THEN 'UX' WHEN 'PK' THEN 'PK' WHEN 'N' THEN 'NN' WHEN 'C' THEN 'CK' 
        END + '_' + ltrim(rtrim(obj_table.name)) + '_' + columns.NAME + ']' +
        CASE obj_Constraint.type WHEN 'D' THEN ' DEFAULT (' + dc.definition +') FOR [' + columns.NAME + ']'
        WHEN 'C' THEN ' CHECK (' + cc.definition +')'
        ELSE '' END +
        ';' As 'Right_Explicit_Constraint'
    FROM   sys.objects obj_table 
        JOIN sys.objects obj_Constraint ON obj_table.object_id = obj_Constraint.parent_object_id 
        JOIN sys.sysconstraints constraints ON constraints.constid = obj_Constraint.object_id 
        JOIN sys.columns columns ON columns.object_id = obj_table.object_id 
            AND columns.column_id = constraints.colid 
        left join sys.schemas sss on obj_Constraint.schema_id=sss.schema_id 
        left join sys.default_constraints dc on dc.object_id = obj_Constraint.object_id
        left join sys.check_constraints cc on cc.object_id = obj_Constraint.object_id
    WHERE obj_Constraint.type_desc LIKE '%CONSTRAINT'
    AND RIGHT(obj_Constraint.name,10) LIKE '[_][_]________' --match double underscore + 8 chars of anything
    AND RIGHT(obj_Constraint.name,8) LIKE '%[A-Z]%'          --Ensure alpha in last 8
    AND RIGHT(obj_Constraint.name,8) LIKE '%[0-9]%'                 --Ensure numeric in last 8
    AND RIGHT(obj_Constraint.name,8) not LIKE '%[^0-9A-Z]%' --Ensure no special chars