Note that there are some explanatory texts on larger screens.

plurals
  1. POSQL Query Substring Query
    primarykey
    data
    text
    <p>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:</p> <blockquote> <p>01_1234_ABC_TESTFOO<br> 02_2234_YES_FOO<br> 03_77653234_NO_BAR<br> 04_10922234_BLUE_TESTBAR<br> 05_8372_SKY_FOOBAR </p> </blockquote> <p>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:</p> <pre><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 </code></pre> <p>This returns:</p> <pre><code> element1 element2 01 1234 02 2234 03 77653234 04 10922234 05 8372 </code></pre> <p>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.</p> <p>See below for code to generate test data.</p> <pre><code>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') </code></pre> <p>Thanks</p> <p>Nimi</p> <p>Edit: Ideally, I'd like to achieve this without using a function but any solutions welcome!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload