简体   繁体   中英

Unable to get table column constraint in T-SQL

I have to create a T-SQL script to update the column datatype but the default constraints do not allow it so I have to first remove the constraints and then alter the column.

I have tried to pass the table column constraint but it does not work.

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
                        AND columns.NAME = 'trans_reject_id'
WHERE 
    obj_table.NAME = 'abc_transaction_table'
ORDER BY 
    'table'


ALTER TABLE abc_transaction_table 
    DROP CONSTRAINT DF__abc_trans__ach_r__575DE8F7

Any help would be appreciated.

Try something like this

SELECT dc.name constraint_name, 
       schema_name(dc.schema_id) schema_name, 
       object_name(dc.parent_object_id) table_name,
       c.name column_name
FROM sys.default_constraints dc
join sys.columns c 
  on dc.parent_column_id = c.column_id
 and dc.parent_object_id = c.object_id

To Alter column constraint you need to write your query in this way:

DECLARE @CONSTRAINT AS VARCHAR(255)
 SET @CONSTRAINT = (SELECT obj_Constraint.NAME AS '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
            WHERE obj_table.NAME='abc_transaction_table'
            AND columns.Name = 'trans_reject_id'
            )
 DECLARE @REMOVE_CONSTARINT VARCHAR(255)
 SET @REMOVE_CONSTARINT = 'ALTER TABLE abc_transaction_table DROP CONSTRAINT' + @CONSTRAINT
 EXEC(@REMOVE_CONSTARINT)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM