SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 SQL select and update with case statement
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

emyk
Yak Posting Veteran

50 Posts

Posted - 06/20/2013 :  13:42:53  Show Profile  Reply with Quote
I need to do a select of a column and if the length of the selected column not equals to 4 then update the column (left Pad with zero's). Expected column length's are 1,2,3,4.


UPDATE table1
SET col1 = 
(CASE WHEN Len(col1) = 3 THEN '0' + col1 
      WHEN Len(col1) = 2 THEN '00' + col1
      WHEN Len(col1) = 1 THEN '000' + col1
ELSE col1  END)
and col1 IN (select col1 from table1 where LEN(col1) <> 4 ) 

Sample Data:
Col1
010
02
3
430
0210

Desire output:
Col1
0010
0002
0003
0430
0210

MIK_2008
Flowing Fount of Yak Knowledge

Pakistan
1052 Posts

Posted - 06/20/2013 :  13:54:46  Show Profile  Reply with Quote
SELECT Right('0000'+Col1,4) FROM Table1 WHERE Len(Col1)<>4;

If the result of the above query is the desired one then

UPDATE Table1 SET Col1=Right('0000'+col1,4)
WHERE Len(Col1)<>4



Cheers
MIK
Go to Top of Page

shan007
Starting Member

USA
17 Posts

Posted - 06/20/2013 :  16:37:43  Show Profile  Reply with Quote
your request can be simplified without case statement as in below. Let me know if it helps.

Assume col1 is varchar type

select REPLICATE(0,4-LEN(col1)) + col1
from table1 where Len(col1)<>4

==============================
I'm here to learn new things everyday..
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.05 seconds. Powered By: Snitz Forums 2000