简体   繁体   中英

How to combine If statement with Substring command in SQL?

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

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM