Wednesday, February 14, 2007

Drop default constraint

Somebody created table like this:

CREATE TABLE [dbo].[MyTable] (
...
[MyField] [bit] NOT NULL DEFAULT (1),
...
) ON [PRIMARY]

I need to do some changes, but first I should drop constraints and after changes, create again. Oops, I don't know constrain name, because somebody used bad style in creation tables.
I need to execute SQL query like following
ALTER TABLE [dbo].[TreeNodeRelation] DROP CONSTRAINT [DF__MyTable__MyField__2B3F6F97] - but we cannot be sure that name will be same on all installations because it is autogenerated during "create table".

Solution. Following example receives name of default constraint for the specific field, and if it is exists, drop it.


declare @cnstname sysname
declare @sql nvarchar(4000)

select @cnstname = [name] from sysobjects as so
where xtype = 'D' and parent_obj = object_id('dbo.MyTable')
and col_name(parent_obj, info) = 'MyField'

if @cnstname is not null
begin
set @sql = N'alter table dbo.MyTable drop constraint ' + @cnstname
execute sp_executesql @sql
end

No comments: