简体   繁体   English

无法在 T-SQL 中获取表列约束

[英]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.我必须创建一个 T-SQL 脚本来更新列数据类型,但默认约束不允许这样做,所以我必须首先删除约束然后更改列。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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