从默认约束中获取值

时间:2022-07-27 18:38:11

I need to change a default constraint value from 0 to 1. This is done easy with:

我需要将默认的约束值从0更改为1。这很容易做到:

ALTER TABLE table DROP CONSTRAINT X
ALTER TABLE table ADD CONSTRAINT X default (1) for table.column

The problem is that I don't want to drop and create a new constraint every time I run modelupdate on my database. That's why I want to run this code IF the value of the constraint is 0.

问题是,我不希望每次在数据库上运行modelupdate时删除并创建一个新的约束。这就是为什么如果约束值为0,我要运行这段代码。

Is it possible to check the value of a default constraint in SQL, if yes, how?

是否可以检查SQL中的默认约束的值,如果可以,如何检查?

1 个解决方案

#1


5  

You can find the "definition" of the default constraint like this:

您可以找到默认约束的“定义”如下:

SELECT 
    DefaultConstraintName = df.name,
    df.definition
FROM 
    sys.default_constraints df
INNER JOIN 
    sys.tables t ON df.parent_object_id = t.object_id
INNER JOIN 
    sys.columns c ON c.object_id = df.parent_object_id AND df.parent_column_id = c.column_id
WHERE 
    t.Name = N'YourTableNameHere'
    AND c.Name = N'YourColumnNameHere'

That however will be returning a string representation of your default value - not the actual value itself (in whatever datatype it is). But that might help you find what you need

但是,它将返回默认值的字符串表示形式——而不是实际值本身(无论数据类型是什么)。但这可能会帮助你找到你需要的东西。

#1


5  

You can find the "definition" of the default constraint like this:

您可以找到默认约束的“定义”如下:

SELECT 
    DefaultConstraintName = df.name,
    df.definition
FROM 
    sys.default_constraints df
INNER JOIN 
    sys.tables t ON df.parent_object_id = t.object_id
INNER JOIN 
    sys.columns c ON c.object_id = df.parent_object_id AND df.parent_column_id = c.column_id
WHERE 
    t.Name = N'YourTableNameHere'
    AND c.Name = N'YourColumnNameHere'

That however will be returning a string representation of your default value - not the actual value itself (in whatever datatype it is). But that might help you find what you need

但是,它将返回默认值的字符串表示形式——而不是实际值本身(无论数据类型是什么)。但这可能会帮助你找到你需要的东西。