0

I need to create or, if it is exists, change default value for an existing column at table users.

I found how can i create/set default value for that column at this link: How to set a default value for an existing column

But I need a conditional statement. I mean, if a default value exists, it should be changed, if not, it should be created.

Which query do I need to execute for this problem?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
iedmrc
  • 742
  • 2
  • 8
  • 21

2 Answers2

2

You can't modify a default value, the single way is to drop first the constraint:

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_someName]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[users] DROP CONSTRAINT [DF_someName]
END

and you create the new one :

ALTER TABLE [dbo].[users] ADD  CONSTRAINT [DF_someName]  DEFAULT N'NewValue' FOR [columnName]
Malainine
  • 133
  • 5
1

You don't. You determine if a default constraint exists using something like this and drop it if it does. Then you add the default constraint that you need.

SMor
  • 2,830
  • 4
  • 11
  • 14