SQL Server的逗号分隔输入字符串

时间:2015-10-05 14:44:48

标签: sql sql-server comma boolean-logic

Hello SQL Server专家。请帮助我有效地将布尔逻辑(And,Or)应用于SQLsServer中以逗号分隔的输入字符串。

示例:

cv2.dft

DECLARE @ATable TABLE(ID INT, Value varchar(50)) INSERT INTO @ATable VALUES (1, 'A'), (1, 'B'), (1, 'C'), (2, 'C'), (2, 'D'), (3, 'A'), (4, 'B') declare @inputStr varchar(max) set @inputStr = 'A,B,C,D' declare @andOr varchar(30) -- can be either 'and' or 'or' ,我想获得具有A和B值的ID。在上表中,结果将是Id 1的数据。因此结果将是

if @andOr = 'and'

ID | Values ----------- 1 | A,B,C ,我想获得值为A或B的ID。在上表中,结果将是Id 1,3和4的数据。因此结果将是

if @andOr = 'or'

感谢。

1 个答案:

答案 0 :(得分:2)

请测试以下SQL Select语句

首先要注意的是SQL string split function 您可以在数据库上创建用户定义的拆分功能的副本

我使用COUNT() aggregate function with Partition By子句。对于程序员来说,这也是T-SQL的一个很大的增强。我用它来检查所有输入参数字符串片段是否与@ATable值匹配

最后一招是string concatenation in SQL用于显示。我使用" For XML Path"用于字符串连接以满足您的要求

DECLARE @ATable TABLE(ID INT, Value varchar(50))
INSERT INTO @ATable VALUES (1,'A'),(1,'B'),(1,'C'),(2,'C'),(2,'D'),(3,'A'),(4,'B')

declare @inputStr varchar(max)
set  @inputStr='A,B'
declare @andOr varchar(30) 

set @andOr='and'

SELECT
  t.ID,
  STUFF(
    (
      SELECT ',' + t1.Value
      FROM @ATable t1
      WHERE t1.ID = t.ID
      FOR XML PATH(''),TYPE
      ).value('.','VARCHAR(MAX)'
    ), 1, 1, '') as [Values]
FROM (
    select 
        distinct ID
    from (
    select
        s.cnt, t.*, 
        tcount = count(t.value) over (partition by t.id)
    from (
        select *, cnt = count(*) over (partition by 1) from dbo.split(@inputStr,',') s
    ) s
    left join @ATable t on s.val = t.value
    ) r
    where tcount = cnt
) t

set @andOr='or'

SELECT
  t.ID,
  STUFF(
    (
      SELECT ',' + t1.Value
      FROM @ATable t1
      WHERE t1.ID = t.ID
      FOR XML PATH(''),TYPE
      ).value('.','VARCHAR(MAX)'
    ), 1, 1, '') as [Values]
FROM (
    select
        distinct t.ID
    from dbo.split(@inputStr,',') s
    inner join @ATable t on s.val = t.value
) t

结果是 enter image description here