按IN LIST子句选择结果

时间:2015-01-29 21:28:23

标签: sql-server tsql

这是我的Group表:

+------+----------+------------------------+----------------+
|  Id  | IdParent |        DateEdit        |     seeds      |
+------+----------+------------------------+----------------+
| 1000 | NULL     | 2015-01-29 17:37:31.74 | 1001,1002,1003 |
+------+----------+------------------------+----------------+

这是products表:

+----+--------+-------------+---------+-----------+
| Id | IdKala | IdGroupChar | IdGroup |   Matn    |
+----+--------+-------------+---------+-----------+
|  1 |    101 |        1001 |    1001 | Product 1 |
|  2 |    102 |        1001 |    1001 | Product 2 |
|  3 |    103 |        1004 |    1004 | Product 3 |
|  3 |    104 |        1006 |    1006 | Product 4 |
|  3 |    105 |        1003 |    1003 | Product 5 |
+----+--------+-------------+---------+-----------+

我需要选择IdGroupChar在种子中的所有记录

select Id, IdKala, IdGroupChar, IdGroup, Matn 
from products 
where (IdGroupChar IN (select seeds 
                       from Groups where id=1000)

由于种子是字段内容,因此返回空表。如果种子是记录列表,它将返回结果。 我该怎么办?

2 个答案:

答案 0 :(得分:1)

请尝试

SELECT 
    Id, IdKala, IdGroupChar, IdGroup, Matn 
FROM 
    products 
    INNER JOIN Groups 
      ON Groups.id = 1000
        AND PATINDEX ('%,' + LTRIM(RTRIM(CONVERT(NVARCHAR(100),
                                               products.IdGroupChar)
                                       )) + ',%', ',' + Groups.seeds + ',') <> 0

Here on MSDN您可能会找到有关PATINDEX功能的文档。

只有当seeds中的vaules总是以逗号,符号(没有空格)分隔时,上述解决方案才有效。

我希望它有所帮助。

答案 1 :(得分:-5)

我选了一个变量@SEEDS并将种子字符串放在这个变量中。这样我们就可以将其传递给分割函数。你可以这样做:

DECLARE @SEEDS VARCHAR(MAX) = (select seeds from Groups where id=1000)

select A.Id, A.IdKala, A.IdGroupChar, A.IdGroup, A.Matn 
from products as a 
INNER JOIN FNSPLIT(@SEEDS , ',') AS B ON A.IdGroupChar = B.ITEM

您需要拆分种子并将其转换为行。为此,有一个名为fnsplit的用户定义函数。您需要在数据库中添加此功能。