|
|
|
SSC 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.
|
|
|
|
|
Hall of Fame
       
Group: General Forum Members
Last Login: Today @ 6:35 AM
Points: 3,046,
Visits: 1,303
|
|
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
|
|
|
|
|
SSCommitted
      
Group: General Forum Members
Last Login: Tuesday, January 15, 2013 11:11 AM
Points: 1,945,
Visits: 2,782
|
|
>> 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. <<
We have no idea what your column looks like, since you did not bother with DDL. You are still thinking of procedural code and do not know that DDl is declarative. Use string functions to constrain string data elements. Here is an way to keep out the bad data:
CREATE TABLE Foobar (.. vague_column CHAR(2) NOT NULL CHECK (vague_column LIKE '[0-9][0-9]'), ..);
>> I am using check constraint to accomplish this. But this is not working..Any help would be appreciated.
CONSTRAINT CheckColLength CHECK (CASE WHEN LEN(col) < 2 THEN '0' + col ELSE col END = 1))
Since this is a fixed length attribute, it should be in a fixed length column. From your narrative, CHAR(2) NOT NULL is the best guess. You then use the CASE expression (not CASE statement) to return a string, which you compare to an integer. That makes no sense.
Books in Celko Series for Morgan-Kaufmann Publishing Analytics and OLAP in SQL Data and Databases: Concepts in Practice Data, Measurements and Standards in SQL SQL for Smarties SQL Programming Style SQL Puzzles and Answers Thinking in Sets Trees and Hierarchies in SQL
|
|
|
|