Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the Default Value Constraint exists?

I am using SQL server 2008. I need to find if default value constraint does not exist then create it. Here is what I have tried.

IF (NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME ='MyConstraint')) BEGIN     ALTER TABLE [XX] ADD  CONSTRAINT [MyConstraint]  DEFAULT ((-1)) FOR [XXXX] END GO 
like image 778
Imran Qadir Baksh - Baloch Avatar asked Dec 11 '12 10:12

Imran Qadir Baksh - Baloch


People also ask

How do I check if a constraint exists in a table?

As of SQL Server 2016, you can just use the IF EXISTS keywords. I'm using SQL Server 2019, but this mentions that it was available since SQL Server 2016. The SQL Server docs mention it here under the ALTER TABLE page, and not under this Delete Check Constraints page.

How do you check constraints on a table in SQL?

Enable a Check Constraint The syntax for enabling a check constraint in SQL Server (Transact-SQL) is: ALTER TABLE table_name WITH CHECK CHECK CONSTRAINT constraint_name; table_name.


2 Answers

if not exists (     select *       from sys.all_columns c       join sys.tables t on t.object_id = c.object_id       join sys.schemas s on s.schema_id = t.schema_id       join sys.default_constraints d on c.default_object_id = d.object_id     where t.name = 'table'       and c.name = 'column'       and s.name = 'schema')   .... 
like image 122
RichardTheKiwi Avatar answered Sep 19 '22 20:09

RichardTheKiwi


I find this to be easier:

IF OBJECT_ID('SchemaName.MyConstraint', 'D') IS NULL BEGIN     -- create it here END 
like image 27
David Sherret Avatar answered Sep 20 '22 20:09

David Sherret