all groups > sql server programming > july 2006 >
You're in the

sql server programming

group:

remove leading , from varchar field


remove leading , from varchar field TG
7/25/2006 9:17:21 PM
sql server programming:
Hi!

I have a varchar field called 'error_code' that looks like this

,C101,C102 etc

It can also look like

C100,C101,C103

depending on the validation errors.

I need to remove the , when is the firt character.
I tried using ltrim but it does nothing.

I also tried using left(error_code) - 1 and get a conversion error.

Any help would be greatly appreciated.

Thanks!

TG
Re: remove leading , from varchar field Chris Lim
7/25/2006 9:28:28 PM
[quoted text, click to view]

Just use a CASE expression to check if the first character is a comma,

e.g. SELECT CASE WHEN LEFT(YourColumn, 1) = ',' THEN RIGHT(YourColumn,
LEN(YourColumn) - 1) ELSE YourColumn END

Chris
RE: remove leading , from varchar field Omnibuzz
7/25/2006 9:38:01 PM
try this.. :)
declare @a varchar(100)
set @a = ',C101,C102,C103'

select replace(replace('!' +@a,'!,',''),'!','')

set @a = 'C101,C102,C103'

select replace(replace('!' +@a,'!,',''),'!','')

--
-Omnibuzz (The SQL GC)

http://omnibuzz-sql.blogspot.com/


Re: remove leading , from varchar field Uri Dimant
7/26/2006 12:00:00 AM
TG
Take a look at REPLACE function in the BOL


[quoted text, click to view]

Re: remove leading , from varchar field Tom Cooper
7/26/2006 12:32:17 AM
Use Case and Substring, something like:

Case When Left(error_code,1) = ',' Then
Substring(error_code,2,Len(error_code) - 1) Else error_code End

Tom

[quoted text, click to view]

Re: remove leading , from varchar field TG
7/26/2006 6:45:58 AM
Thank you, tom. It works like a charm.

Thank you to all who replied.

TG


[quoted text, click to view]
Re: remove leading , from varchar field Hugo Kornelis
7/26/2006 10:33:56 PM
[quoted text, click to view]

Hi TG,

LTRIM is for removing leading spaces only.

Try this:

SELECT CASE WHEN LEFT(error_code, 1) <> ','
THEN error_code
ELSE STUFF(error_code, 1, 1, '')
END
FROM (SELECT ',C101,C102' AS error_code
UNION SELECT 'C100,C101,C103') AS der;

Or, if you prefer sneaky, unmaintainable, but short code, try this:

SELECT STUFF(error_code, 1, CHARINDEX(',', LEFT(error_code, 1)), '')
FROM (SELECT ',C101,C102' AS error_code
UNION SELECT 'C100,C101,C103') AS der;

--
Re: remove leading , from varchar field Hugo Kornelis
7/26/2006 10:35:38 PM
[quoted text, click to view]

Hi Uri,

REPLACE can't be used here - that would remove all comma's from the
string instead of just the leading comma.

Unless you had something in your mind such as

SELECT REPLACE(LTRIM(REPLACE(error_code, ',', ' ')), ' ', ',')
FROM (SELECT ',C101,C102' AS error_code
UNION SELECT 'C100,C101,C103') AS der;

--
AddThis Social Bookmark Button