Click here to monitor SSC
SQLServerCentral is supported by Redgate
 
Log in  ::  Register  ::  Not logged in
 
 
 


Check Constraint with Case Statement


Check Constraint with Case Statement

Author
Message
SqlSavvy
SqlSavvy
SSC-Enthusiastic
SSC-Enthusiastic (177 reputation)SSC-Enthusiastic (177 reputation)SSC-Enthusiastic (177 reputation)SSC-Enthusiastic (177 reputation)SSC-Enthusiastic (177 reputation)SSC-Enthusiastic (177 reputation)SSC-Enthusiastic (177 reputation)SSC-Enthusiastic (177 reputation)

Group: General Forum Members
Points: 177 Visits: 300
I need to check the column and if the value entered is 1 digit, I need to make it two digits like 01. If the value is two digit already, just leave it alone.

I am using check constraint to accomplish this. But this is not working..Any help would be appreciated.

ALTER TABLE [dbo].TableName WITH CHECK
ADD CONSTRAINT [CheckColLength] CHECK (case when len(col) < 2 THEN '0' + col else col end=1))
GO


Can we use Case statement in check constraint?

Thanks for your help.
Duncan Pryde
Duncan Pryde
Hall of Fame
Hall of Fame (3.5K reputation)Hall of Fame (3.5K reputation)Hall of Fame (3.5K reputation)Hall of Fame (3.5K reputation)Hall of Fame (3.5K reputation)Hall of Fame (3.5K reputation)Hall of Fame (3.5K reputation)Hall of Fame (3.5K reputation)

Group: General Forum Members
Points: 3474 Visits: 1552
Hi

You can't use a check constraint to alter values - it can only check the values and generate an error if they are incorrect.

You can however use a trigger to do what you want to do. You'd want a FOR UPDATE, INSERT trigger which checks the column value and changes it if necessary. Have a look at trigger syntax and get back if you have any problems.

There may of course be other ways of doing this, so let's see what else people come up with!

Duncan
Go


Permissions

You can't post new topics.
You can't post topic replies.
You can't post new polls.
You can't post replies to polls.
You can't edit your own topics.
You can't delete your own topics.
You can't edit other topics.
You can't delete other topics.
You can't edit your own posts.
You can't edit other posts.
You can't delete your own posts.
You can't delete other posts.
You can't post events.
You can't edit your own events.
You can't edit other events.
You can't delete your own events.
You can't delete other events.
You can't send private messages.
You can't send emails.
You can read topics.
You can't vote in polls.
You can't upload attachments.
You can download attachments.
You can't post HTML code.
You can't edit HTML code.
You can't post IFCode.
You can't post JavaScript.
You can post emoticons.
You can't post or upload images.

Select a forum

































































































































































SQLServerCentral


Search