0

I have two types of entries in one column. One type starts with V2, the other starts with a digit. How do I write a query in SQL where I can extract different part of the string based on how it starts?

TextStringColumn
V2|T:GSK|1000000|S1:TES|S2:N/A|Q:24|S:0.5gx3|PD:2020-10-22|C:QQ
2000308|S1:BES|T:SKY|Q:16446G|BSI:BPKGVAXQOHZFWGE

I wrote

SELECT TextStringColumn, If(TextStringColumn like 'V2%',SUBSTRING(TextStringColumn ,10,7),SUBSTRING(TextStringColumn ,1,7)) As NumberCol
FROM TestTable

But I keep getting syntax errors.

Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'If'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near ','.

The desired result will be

TextStringColumn                                                           NumberCol              
V2|T:GSK|1000000|S1:TES|S2:N/A|Q:24|S:0.5gx3|PD:2020-10-22|C:QQ            1000000
2000308|S1:BES|T:SKY|Q:16446G|BSI:BPKGVAXQOHZFWGE                          2000308

1
  • The official docs should always be your first port of call. Commented Nov 17, 2020 at 19:20

2 Answers 2

1

You may use a CASE expression:

SELECT
    CASE WHEN TextStringColumn LIKE 'V2%'
         THEN SUBSTRING(TextStringColumn, 10, 7)
         ELSE SUBSTRING(TextStringColumn, 1, 7) END AS NumberCol
FROM TestTable;

The above logic assumes the only two varieties of strings are those which start with V2, and those which do not start with V2.

Sign up to request clarification or add additional context in comments.

Comments

1

If the strings are variable length ... consider a little JSON

Example

Declare @YourTable Table ([TextStringColumn] varchar(100))  Insert Into @YourTable Values 
 ('V2|T:GSK|1000000|S1:TES|S2:N/A|Q:24|S:0.5gx3|PD:2020-10-22|C:QQ')
,('2000308|S1:BES|T:SKY|Q:16446G|BSI:BPKGVAXQOHZFWGE')
 
Select A.* 
      ,Val = case when [TextStringColumn] like 'V2%'
                  then JSON_VALUE(S,'$[2]')
                  else JSON_VALUE(S,'$[0]') end
 From @YourTable A
 Cross Apply ( values ( '["'+replace([TextStringColumn],'|','","')+'"]' ) ) B(S)

Returns

TextStringColumn                                                    Val
V2|T:GSK|1000000|S1:TES|S2:N/A|Q:24|S:0.5gx3|PD:2020-10-22|C:QQ     1000000
2000308|S1:BES|T:SKY|Q:16446G|BSI:BPKGVAXQOHZFWGE                   2000308

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.