user3025336
user3025336

Reputation:

Get the value from a default constraint

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

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.

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

Upvotes: 4

Views: 3302

Answers (2)

Venkataraman R
Venkataraman R

Reputation: 12959

You can see the default value for the column from the below information_schema view.

SELECT COLUMN_DEFAULT FROM INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'TableName' and COLUMN_NAME = 'ColumnName'

Upvotes: 0

marc_s
marc_s

Reputation: 754220

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

Upvotes: 8

Related Questions