I have a database column in a SQL Server 2008 database that contains VARCHAR data composed of four elements separated by an underscore; for example:
01_1234_ABC_TESTFOO
02_2234_YES_FOO
03_77653234_NO_BAR
04_10922234_BLUE_TESTBAR
05_8372_SKY_FOOBAR
I need a query to return the first three elements for each row as separate columns. I have managed to separate out the first two elements with the following code:
SELECT DISTINCT SUBSTRING(BarType, 1, CHARINDEX('_', BarType) - 1) as element1,
SUBSTRING(BarType,CHARINDEX('_',BarType)+1,
CHARINDEX('_', SUBSTRING(BarType,CHARINDEX('_',BarType)+1,LEN(BarType)))-1) as element2
FROM dbo.TestDataFoo
This returns:
element1 element2
01 1234
02 2234
03 77653234
04 10922234
05 8372
Could someone help me to get the third element of the data please? I'd also be interested to learn of any alternate methods for dealing with this.
See below for code to generate test data.
CREATE TABLE TestDataFoo (
id int PRIMARY KEY IDENTITY,
DateFoo datetime NOT NULL,
BarType varchar(50) NOT NULL)
INSERT INTO TestDataFoo (DateFoo, BarType)
VALUES(GetDate(), '01_1234_ABC_TESTFOO')
INSERT INTO TestDataFoo (DateFoo, BarType)
VALUES(GetDate(), '02_2234_YES_FOO')
INSERT INTO TestDataFoo (DateFoo, BarType)
VALUES(GetDate(), '03_77653234_NO_BAR')
INSERT INTO TestDataFoo (DateFoo, BarType)
VALUES(GetDate(), '04_10922234_BLUE_TESTBAR')
INSERT INTO TestDataFoo (DateFoo, BarType)
VALUES(GetDate(), '05_8372_SKY_FOOBAR')
Thanks
Nimi
Edit: Ideally, I'd like to achieve this without using a function but any solutions welcome!