How to check if the Default Value Constraint exists?
if not exists(select 1 from sys.default_constraints where name = 'SchemaName.MyConstraint')
begin
-- create it here
end
I find this to be easier:
IF OBJECT_ID('SchemaName.MyConstraint', 'D') IS NULL
BEGIN
-- create it here
END
I was a bit puzzled as to why this simple task was so complicated. In my case, I don't have constraint names - only table and column names. I want to check if they already have a default before trying to add one.
After a bit more digging, I came up with this:
IF (SELECT Column_Default FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'MY_TABLE' AND COLUMN_NAME = 'MY_COLUMN') is NULL
BEGIN
ALTER TABLE [dbo].[MY_TABLE]
ADD DEFAULT ('') FOR [MY_COLUMN]
END
GO
I have to implement this in a ginormous boilerplate script, so the shorter the better.
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')
....