提取每组两个不同字符串之间的每个字符串

时间:2019-01-10 17:17:06

标签: sql sql-server sql-server-2008-r2

例如,如果我有字符串:

'x(abc),y(def),z(ghi)'

如何提取逗号分隔的字符串:

'abc,def,ghi'

或字符串表:

'abc'
'def'
'ghi'
在两个字符串'('')'之间存在

它们以逗号分隔,但是每个“元素”的长度都可以变化。

2 个答案:

答案 0 :(得分:2)

如果对TVF开放。作为TVF,如果您的数据在表格中,则很容易在CROSS APPLY中使用。

示例

Declare @S varchar(max) = 'x(abc),y(def),z(ghi)'

Select * from [dbo].[tvf-Str-Extract](@S,'(',')')

返回

RetSeq  RetPos  RetVal
1       3       abc
2       10      def
3       17      ghi

感兴趣的功能

CREATE FUNCTION [dbo].[tvf-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].[tvf-Str-Extract] (@String,'[[',']]')
*/

答案 1 :(得分:1)

您可以像下面这样使用charindex

declare @temp table        
(val nvarchar(50))

insert into @temp values ('x(abc)')
insert into @temp values ('y(def)')
insert into @temp values ('z(ghi)')

SELECT 
SUBSTRING(val,CHARINDEX('(', val) + 1,CHARINDEX(')', val) - CHARINDEX('(', val) - 1) as Val
from @temp 

参考:SQL Select values inside parenthesis

编辑:如果它是一行,其中包括许多数值,则需要首先基于逗号对其进行分割。对于SQL 2008,多年来我一直在使用此链接中指定的split函数,谢谢Andy:T-SQL split string

创建以下函数:

CREATE FUNCTION dbo.splitstring ( @stringToSplit VARCHAR(MAX) )
RETURNS
 @returnList TABLE ([Name] [nvarchar] (500))
AS
BEGIN

 DECLARE @name NVARCHAR(255)
 DECLARE @pos INT

 WHILE CHARINDEX(',', @stringToSplit) > 0
 BEGIN
  SELECT @pos  = CHARINDEX(',', @stringToSplit)  
  SELECT @name = SUBSTRING(@stringToSplit, 1, @pos-1)

  INSERT INTO @returnList 
  SELECT @name

  SELECT @stringToSplit = SUBSTRING(@stringToSplit, @pos+1, LEN(@stringToSplit)-@pos)
 END

 INSERT INTO @returnList
 SELECT @stringToSplit

 RETURN
END

并查看以下内容:SELECT * FROM dbo.splitstring('x(abc),y(def),z(ghi)')

这样,您可以基于逗号分割数据并使用我提到的第一个charindex策略。