In SQL Server, defaults are defined as constraints associated with a specific column in a table. All constraints are assigned a name; this is important, because once the constraint is created, if you want to modify it you have to reference it by this name. (And I’ll be watching this question, to see if I’m wrong.)
Based on this sample table:
CREATE TABLE MyTable
(
MyTableId int not null
,SomeData varchar(50) not null default 'Foo'
,MoreData datetime not null default CURRENT_TIMESTAMP
)
Step 1: Determine if a constraint exists on a column. Several ways to do this, all involving system views and/or metadata functions. Here’s a quick one, where ‘MyTable’ and ‘SomeData’ could be set as parameters:
SELECT name
from sys.default_constraints
where parent_object_id = object_id('MyTable')
and parent_column_id = columnproperty(object_id('MyTable'), 'SomeData', 'ColumnId')
Try it, and you’ll see that the name generated is essentially random blather. To determine if a default exists on a column, you could do:
IF exists (select name
from sys.default_constraints
where parent_object_id = object_id('MyTable')
and parent_column_id = columnproperty(object_id('MyTable'), 'SomeData', 'ColumnId'))
PRINT 'Default found'
ELSE
PRINT 'NoDefault'
To drop an existing default where you don’t know the name, you’ll have to build dynamic SQL. (that code in the referenced article is wrong, and clearly never tested.) @Călin does it slightly differently than I’d do it, but the idea’s the same:
DECLARE @Command nvarchar(max)
SELECT @Command = 'ALTER TABLE MyTable drop constraint ' + name
from sys.default_constraints
where parent_object_id = object_id('MyTable')
and parent_column_id = columnproperty(object_id('MyTable'), 'SomeData', 'ColumnId')
IF @Command is not null
EXECUTE sp_executeSQL @Command
(With error checking, parameters for the table and and column being checked, and so on.)
Lastly, you can avoid most of this by naming the defaults when you create the constraint, like so:
CREATE TABLE MyTable
(
MyTableId int not null
,SomeData varchar(50) not null
constraint DF_MyTable__SomeData default 'Foo'
,MoreData datetime not null
constraint DF_MyTable__MoreData default CURRENT_TIMESTAMP
)
Or like so:
IF not exists (select name
from sys.default_constraints
where parent_object_id = object_id('MyTable')
and parent_column_id = columnproperty(object_id('MyTable'), 'SomeData', 'ColumnId'))
ALTER TABLE MyTable
add constraint DF_MyTable__SomeData
default 'Foo' for SomeData