解析查询中的SQL字段

时间:2017-03-14 21:05:41

标签: sql parsing

我继承了一个用户个人资料信息数据库,其中包含一个供个人兴趣的专栏。多个兴趣由管道(|)分隔。在SQL查询中,如何使用此值拆分字段:2 | 27 | 33 | 14 | 15

看起来像这样:

2
27
33
14
15

2 个答案:

答案 0 :(得分:0)

确切的语法取决于您使用的dbms。假设您正在使用MSSQL,这是一般语法

STRING_SPLIT ( string , separator )

例如

DECLARE @string_to_be_split NVARCHAR(400) = '2|27|33|14|15'  

SELECT value  
FROM STRING_SPLIT(@string_to_be_split, '|')  
WHERE RTRIM(value) <> '';  

答案 1 :(得分:0)

  

编辑 - 可以发誓我看到了SQL Server

如果不是2016年,几乎任何分割/解析功能都可以。

选项1 - 使用UDF

Declare @YourTable table (ID int,Interests varchar(250))
Insert Into @YourTable values
(1,'2|27|33|14|15')

Select A.ID
      ,B.*
 From  @YourTable A
 Cross Apply [dbo].[udf-Str-Parse](A.Interests,'|') B

选项2 - 没有UDF

Select A.ID
      ,B.*
 From  @YourTable A
 Cross Apply (
                Select RetSeq = Row_Number() over (Order By (Select null))
                      ,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
                From  (Select x = Cast('<x>' + replace((Select replace(A.Interests,'|','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as X
                Cross Apply x.nodes('x') AS B(i)
             ) B

返回

ID  RetSeq  RetVal
1   1       2
1   2       27
1   3       33
1   4       14
1   5       15

感兴趣的UDF

CREATE FUNCTION [dbo].[udf-Str-Parse] (@String varchar(max),@Delimiter varchar(10))
Returns Table 
As
Return (  
    Select RetSeq = Row_Number() over (Order By (Select null))
          ,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
    From  (Select x = Cast('<x>' + replace((Select replace(@String,@Delimiter,'§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as X
    Cross Apply x.nodes('x') AS B(i)
);
--Thanks Shnugo for making this XML safe
--Select * from [dbo].[udf-Str-Parse]('Dog,Cat,House,Car',',')
--Select * from [dbo].[udf-Str-Parse]('John Cappelletti was here',' ')
--Select * from [dbo].[udf-Str-Parse]('this,is,<test>,for,< & >',',')