About SQL uses charindex, substring and other functions to extract values at different positions

Regarding SQL to extract the values ​​in different positions, you may often need to use it. Today, when extracting the SSRS report, record it here.

The original data is:


Because each value is followed by a common match (semicolon), it is positioned according to the semicolon

1) It is easier to take the value before the first semicolon

Code 1 is: left (remark, charindex (';', remark) -1) as zzno or: SUBSTRING (remark, 1, charindex (';', remark) -1) The two effects are the same

2) Take the workno field and take it twice:

One: Take the value after the first semicolon: substring (remark, charindex (';', remark, 0) + 1, LEN (remark))  

Two: according to the first extraction method, then nested

代码结合为:SUBSTRING(remark,1,charindex(';',remark)-1)
 ,left(substring(remark,charindex(';',remark,0)+1,LEN(remark)),CHARINDEX(';',
 substring(remark,charindex(';',remark,0)+1,LEN(remark))
 )-1) 

Three: Take the remark2 field value, this method refers to a great god of CSDN, judge if there are more than two semicolons (;) to intercept the string, otherwise it is empty ''

代码为:case when len(remark)-len(replace(remark,';',''))>2 
                              then substring(remark,charindex(';',remark,charindex(';',remark,1)+1)+1,

charindex(';',remark,charindex(';',remark,charindex(';',remark,1)+1)+1)-charindex(';',remark,charindex(';',remark,1)+1)-1)           

                            else '' end as remark2

Four: take the value in square brackets []

代码如:substring(remark,charindex('[',remark,0)+1,len(remark)-charindex(']',reverse(remark),0)-charindex('[',remark,0))

The above four methods take out the values ​​of different positions, the effect is as shown above



Published 22 original articles · praised 7 · 100,000+ views

Guess you like

Origin blog.csdn.net/qyx0714/article/details/72877791