简体   繁体   中英

Extracting a string from data field in sql server

I am trying to select the string between every pair <....> in the fifth column "QuestionTags".

here is a sample of the data:

在此处输入图片说明

i used CHARINDEX function but it returned me an integer.

i also used SUBSTRING but it asks me to define the character index and length of string.

Any suggestions?

If you are open to a Table-Valued-Function and not using 2016.

Tired of extracting strings (charindex,left,right,substring,...), I modified a Parse/Split function to accept two NON-LIKE delimiters. In your case a < and >

Example

Declare @YourTable table (ID int,QuestionTags varchar(max))
Insert Into @YourTable values
 (1,'<php><arrays><cloud><tag-cloud>')
,(2,'<windows><mailto>')

Select A.ID
      ,B.*
 From  @YourTable A
 Cross Apply [dbo].[udf-Str-Extract](A.QuestionTags,'<','>') B

Returns

ID  RetSeq  RetPos  RetVal
1   1       2       php
1   2       7       arrays
1   3       15      cloud
1   4       22      tag-cloud
2   1       2       windows     --<< Second Record
2   2       11      mailto

The UDF if interested

CREATE FUNCTION [dbo].[udf-Str-Extract] (@String varchar(max),@Delimiter1 varchar(100),@Delimiter2 varchar(100))
Returns Table 
As
Return (  

with   cte1(N)   As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
       cte2(N)   As (Select Top (IsNull(DataLength(@String),0)) Row_Number() over (Order By (Select NULL)) From (Select N=1 From cte1 N1,cte1 N2,cte1 N3,cte1 N4,cte1 N5,cte1 N6) A ),
       cte3(N)   As (Select 1 Union All Select t.N+DataLength(@Delimiter1) From cte2 t Where Substring(@String,t.N,DataLength(@Delimiter1)) = @Delimiter1),
       cte4(N,L) As (Select S.N,IsNull(NullIf(CharIndex(@Delimiter1,@String,s.N),0)-S.N,8000) From cte3 S)

Select RetSeq = Row_Number() over (Order By N)
      ,RetPos = N
      ,RetVal = left(RetVal,charindex(@Delimiter2,RetVal)-1) 
 From  (
        Select *,RetVal = Substring(@String, N, L) 
         From  cte4
       ) A
 Where charindex(@Delimiter2,RetVal)>1

)
/*
Max Length of String 1MM characters

Declare @String varchar(max) = 'Dear [[FirstName]] [[LastName]], ...'
Select * From [dbo].[udf-Str-Extract] (@String,'[[',']]')
*/

If you can use SQL Server 2016 for this then there is a built in string_split function that will do the job

SELECT *
FROM   YourTable
       OUTER APPLY (SELECT SUBSTRING(value, 2, 8000) value
                    FROM   string_split(QuestionTags, '>')
                    WHERE  value <> '') OA 

A demo in Stack Exchange Data Explorer as it looks like you are using SE data.

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