How do I get constraints on a SQL Server table column

ymdaylpp  于 2023-10-15  发布在  SQL Server
关注(0)|答案(7)|浏览(116)

I have a column called MealType ( VARCHAR ) in my table with a CHECK constraint for {"Veg", "NonVeg", "Vegan"}

That'll take care of insertion.

I'd like to display these options for selection, but I couldn't figure out the SQL query to find out the constraints of a particular column in a table.

From a first glance at system tables in SQL Server, it seems like I'll need to use SQL Server's API to get the info. I was hoping for a SQL query itself to get it.

uxh89sit

uxh89sit1#

Easiest and quickest way is to use:

sp_help 'TableName'
bfrts1fy

bfrts1fy2#

This query should show you all the constraints on a table:

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

can replace the select statement with this:

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

mdfafbf13#

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'
vptzau2j

vptzau2j4#

You can use

sp_helpconstraint 'tableName', 'nomsg'

to get all the constraints for the table.

"sp_help" return far more information.

w8biq8rn

w8biq8rn5#

Thanks to orgtrigger for his example! I improved it to be able to remove unnecessary constraints (and then create their modified versions, if needed). Maybe this code will be useful for anybody.

-- 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
sirbozc5

sirbozc56#

Below is helpful for check and default constraints. I use it for implicit constraints to offer up guidance for what the name should be. If you remove everything after the where clause, it should be good for any check/default constraints.

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
frebpwbc

frebpwbc7#

Query to fetch constraint information:

SELECT t1.TABLE_NAME, t1.COLUMN_NAME, STRING_AGG(COALESCE(t1.CONSTRAINT_TYPE,''),','), t1.ORDINAL_POSITION, STRING_AGG(COALESCE(t1.reference_table,''),'') AS reference_table, STRING_AGG(COALESCE(t1.reference_column,''),'') AS reference_column
FROM
(SELECT c.TABLE_NAME, c.COLUMN_NAME, tc.CONSTRAINT_TYPE, ORDINAL_POSITION, t2.TABLE_NAME AS reference_table, t2.COLUMN_NAME AS reference_column
FROM INFORMATION_SCHEMA.COLUMNS c
LEFT JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu ON c.COLUMN_NAME = ccu.COLUMN_NAME AND c.TABLE_NAME = ccu.TABLE_NAME
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc ON ccu.CONSTRAINT_NAME = tc.CONSTRAINT_NAME
LEFT JOIN (SELECT  ccu1.TABLE_NAME, ccu1.COLUMN_NAME, rc.UNIQUE_CONSTRAINT_NAME, rc.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc 
LEFT JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu1 ON ccu1.CONSTRAINT_NAME = rc.UNIQUE_CONSTRAINT_NAME)t2
ON ccu.CONSTRAINT_NAME = t2.CONSTRAINT_NAME
GROUP BY c.TABLE_NAME, c.COLUMN_NAME, tc.CONSTRAINT_TYPE,ORDINAL_POSITION, t2.TABLE_NAME, t2.COLUMN_NAME)t1
GROUP BY t1.TABLE_NAME, t1.COLUMN_NAME,t1.ORDINAL_POSITION
ORDER BY t1.TABLE_NAME, t1.ORDINAL_POSITION

相关问题