从单行选择“逗号分隔值的子查询”

时间:2016-09-22 15:48:06

标签: sql sql-server

从选择查询中我得到的是单行中的值,而不是不同的行:

Id        Statuses
---     -------------
1       Released,In Progress,Completed

现在我想编写一个查询,以便获取状态中的所有订单:

Select * from Orders where Status in (Select Statusesfrom StatusTable)

3 个答案:

答案 0 :(得分:1)

采用其中一种分离器。你可以自己编写,但你会发现很多东西已经用于研究这些:

http://www.sqlservercentral.com/articles/Tally+Table/72993/

这会将您的值拆分为包含单个列的表。您可以在运行该功能后加入此功能,如:

Select o.* from Orders o
inner join splitTable s on o.keyColumn = s.Column

答案 1 :(得分:1)

经过多次讨论(如下所示)和测试后,我修改了我的解析函数。新函数将解析250,000个字符串,在400毫秒内生成1,889,108行。

Declare @YourTable table (Id int,Statuses varchar(250))
Insert into @YourTable values 
(1,'Released,In Progress,Completed'),
(2,'Released,In Progress')

Select A.ID
      ,B.* 
from @YourTable A
Cross Apply (Select * from [dbo].[udf-Str-Parse-8K](A.Statuses,',')) B
Order By ID,Key_PS

返回

ID  Key_PS  Key_Value   Key_Pos
1   1       Released    1
1   2       In Progress 10
1   3       Completed   22
2   1       Released    1
2   2       In Progress 10

UDF(如果需要)

CREATE FUNCTION [dbo].[udf-Str-Parse-8K](@String varchar(8000), @Delimiter varchar(50))
Returns Table 
As

--Usage: Select * from [dbo].[udf-Str-Parse-8K]('Dog,Cat,House,Car',',')
--       Select * from [dbo].[udf-Str-Parse-8K]('John||Cappelletti||was||here','||')
--       Select * from [dbo].[udf-Str-Parse-8K]('The quick brown fox',' ')

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 a, cte1 b, cte1 c, cte1 d) A ),
        cte3(N)   As (Select 1 Union All Select t.N+DataLength(@Delimiter) From cte2 t Where Substring(@String,t.N,DataLength(@Delimiter)) = @Delimiter),
        cte4(N,L) As (Select S.N,IsNull(NullIf(CharIndex(@Delimiter,@String,s.N),0)-S.N,8000) From cte3 S)

   Select Key_PS    = Row_Number() over (Order By A.N)
         ,Key_Value = Substring(@String, A.N, A.L) 
         ,Key_Pos   = A.N
   From   cte4 A
)

来自http://www.sqlservercentral.com/articles/Tally+Table/72993/

的几个调整

答案 2 :(得分:0)

如果您使用的是SQL Server 2016,请使用STRING_SPLIT()函数。

     SELECT *
     FROM Orders 
      WHERE Status IN (SELECT Value FROM  StatusTable
                         CROSS APPLY STRING_SPLIT(Statuses,','))