Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase

Check Constraint with Case Statement Expand / Collapse
Author
Message
Posted Thursday, August 5, 2010 7:12 PM
SSC Journeyman

SSC JourneymanSSC JourneymanSSC JourneymanSSC JourneymanSSC JourneymanSSC JourneymanSSC JourneymanSSC Journeyman

Group: General Forum Members
Last Login: Friday, March 16, 2012 3:51 PM
Points: 83, 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.
Post #964790
Posted Friday, August 6, 2010 2:58 AM
Hall of Fame

Hall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of Fame

Group: General Forum Members
Last Login: Today @ 10:47 AM
Points: 3,352, Visits: 1,513
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
Post #964914
« Prev Topic | Next Topic »

Add to briefcase

Permissions Expand / Collapse