Groups | Blog | Home
all groups > sql server programming > october 2007 >

sql server programming : Using Substring for grouping the new file.


NT
10/6/2007 1:14:18 PM
Hi,

Please help...!
I have a Test_Name then I need to break all the texts from after the word
'cycle' to store into the new field as Comments. Please see example below

Test_Name: 73025-003_BnDcycleRestart-01-045

Here is my SQL statement:

SUBSTRING(Test_Name, CHARINDEX('cycle', Test_Name) + 1, CHARINDEX('-',
Test_Name, CHARINDEX('cycle', Test_Name)) - CHARINDEX('cycle', Test_Name) -
1) AS Comments

The result in the new field Comments supposed to be 'Restart'; however, the
result was 'ycleRestart'. Do I miss anything?

Thank you in advance
--
Tom Cooper
10/6/2007 4:36:11 PM
CHARINDEX('cycle', Test_Name) finds the character where "cycle" BEGINS. So
to get to the first character past "cycle", you need to add 5, not 1. Of
course, when computing the length, since you've now added 5, rather than 1,
you need to shorten the length by 4 more characters. So you want:

Declare @Foo Table (Test_Name varchar(50))
Insert @Foo (Test_Name) Values ('73025-003_BnDcycleRestart-01-045')

Select SUBSTRING(Test_Name, CHARINDEX('cycle', Test_Name) + 5,
CHARINDEX('-', Test_Name, CHARINDEX('cycle', Test_Name))
- CHARINDEX('cycle', Test_Name) - 5) AS Comments
From @Foo

Tom

[quoted text, click to view]

NT
10/6/2007 5:20:11 PM
Excellent...! It worked very well.
--
NT


[quoted text, click to view]
AddThis Social Bookmark Button