dbTalk Databases Forums  

Split a field

comp.databases.ms-sqlserver comp.databases.ms-sqlserver


Discuss Split a field in the comp.databases.ms-sqlserver forum.



Reply
 
Thread Tools Display Modes
  #1  
Old   
chudson007@hotmail.com
 
Posts: n/a

Default Split a field - 05-12-2005 , 10:49 AM






Whats the best way to do the following?

Field1 in Table1 contains numbers and characters seperated by #
Examples: aaa#01, kjhkjhjh#21 and jlkjlkj#123

How can I create two new fields in Table1, one containing what is to
the left of the # and the other what is to the right?

Regards,
Ciarán


Reply With Quote
  #2  
Old   
Hugo Kornelis
 
Posts: n/a

Default Re: Split a field - 05-12-2005 , 04:05 PM






On 12 May 2005 08:49:49 -0700, chudson007 (AT) hotmail (DOT) com wrote:

Quote:
Whats the best way to do the following?

Field1 in Table1 contains numbers and characters seperated by #
Examples: aaa#01, kjhkjhjh#21 and jlkjlkj#123

How can I create two new fields in Table1, one containing what is to
the left of the # and the other what is to the right?

Regards,
Ciarán
Hi Ciarán,

UPDATE MyTable
SET NewCol1 = LEFT(ConcatCol,
CHARINDEX('#', ConcatCol) - 1)
, NewCol2 = SUBSTRING(ConcatCol,
CHARINDEX('#', ConcatCol) + 1,
LEN(ConcatCol))
WHERE ConcatCol LIKE '%#%'

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)


Reply With Quote
  #3  
Old   
chudson007@hotmail.com
 
Posts: n/a

Default Re: Split a field - 05-13-2005 , 05:07 AM



Hugo,

How shoud I modify the SQL so that if there is no '#' in ConcatCol,
then NewCol1 = ConcatCol

Regards,
Ciarán


Reply With Quote
  #4  
Old   
Hugo Kornelis
 
Posts: n/a

Default Re: Split a field - 05-13-2005 , 06:00 PM



On 13 May 2005 03:07:06 -0700, chudson007 (AT) hotmail (DOT) com wrote:

Quote:
Hugo,

How shoud I modify the SQL so that if there is no '#' in ConcatCol,
then NewCol1 = ConcatCol

Regards,
Ciarán
Hi Ciarán,

UPDATE MyTable
SET NewCol1 = CASE
WHEN ConcatCol LIKE '%#%'
THEN LEFT(ConcatCol,
CHARINDEX('#', ConcatCol) - 1)
ELSE ConcatCol
END
, NewCol2 = CASE
WHEN ConcatCol LIKE '%#%'
THEN SUBSTRING(ConcatCol,
CHARINDEX('#', ConcatCol) + 1,
LEN(ConcatCol))
ELSE NULL
END

Or you could simply run two consecutive UPDATE statements (the one from
my first message, followed by an update that sets newcol1 equal to
concatcol for the remaining rows).

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)


Reply With Quote
Reply




Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off



Powered by vBulletin Version 3.5.3
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.