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
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.
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.
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') ....
I find this to be easier:
IF OBJECT_ID('SchemaName.MyConstraint', 'D') IS NULL BEGIN -- create it here END
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With