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
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Get Top 5 characters only
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

kamii47
Constraint Violating Yak Guru

335 Posts

Posted - 08/03/2012 :  04:19:40  Show Profile  Reply with Quote
I have a column brnZipCode which have varchar(9) as possible length.
in select statement I have to populate it in sucha way that if it's length is greater then 5 then take only top 5 characters other wise full brnZipCode .

My current query is in such a way

select DerivedEntryPoint = CASE
WHEN BP.brnZipCode IS NOT NULL THEN BP.brnZipCode
ELSE csm.csmContainerDestinationZip
END
From csm,BP ..........

Kamran Shahid
Principle Engineer Development
(MCSD.Net,MCPD.net)

Abu-Dina
Posting Yak Master

United Kingdom
199 Posts

Posted - 08/03/2012 :  04:24:38  Show Profile  Reply with Quote
case when len(brnZipCode)> 5 then left(brnZipCode, 5) else brnZipCode end
Go to Top of Page

kamii47
Constraint Violating Yak Guru

335 Posts

Posted - 08/03/2012 :  04:42:36  Show Profile  Reply with Quote
it required two case statement i think.
(as if i have to put other fileds data if the brnZipciode is null)
can't it be more simplified?

Kamran Shahid
Principle Engineer Development
(MCSD.Net,MCPD.net)

Go to Top of Page

Abu-Dina
Posting Yak Master

United Kingdom
199 Posts

Posted - 08/03/2012 :  05:39:08  Show Profile  Reply with Quote

isnull(case when len(brnZipCode)> 5 then left(brnZipCode, 5) else csmContainerDestinationZip end, csmContainerDestinationZip)

Edited by - Abu-Dina on 08/03/2012 05:39:23
Go to Top of Page

sunitabeck
Flowing Fount of Yak Knowledge

5152 Posts

Posted - 08/03/2012 :  06:48:30  Show Profile  Reply with Quote
You can use LEFT function without regard to how long the string is. If the string happens to be shorter than the length parameter of the LEFT function, it will simply return the entire string.
DECLARE @x VARCHAR(9);

SET @x = 'ABCDEDGHK';
SELECT LEFT(@x,5);
--- returns 'ABCDE'

SET @x = 'AB';
SELECT LEFT(@x,5);
--- returns 'AB'
If your zip happens to be null and you want to handle that, you can use the COALESCE on top of that. For example,
SELECT COALESCE(LEFT(@x,5),' None ');

Edited by - sunitabeck on 08/03/2012 06:50:07
Go to Top of Page

kamii47
Constraint Violating Yak Guru

335 Posts

Posted - 08/06/2012 :  02:11:57  Show Profile  Reply with Quote
Thanks Sunit

Kamran Shahid
Principle Engineer Development
(MCSD.Net,MCPD.net)

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