select IN LIST 子句的结果

select result by IN LIST clause

这是我的 Group table :

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

这是products table:

+----+--------+-------------+---------+-----------+
| 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 |
+----+--------+-------------+---------+-----------+

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

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

由于 seeds 是字段内容,因此 return 为空 table。如果 seeds 是一个记录列表,它将得到 return 个结果。 我能做什么?

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

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 的用户定义函数。您需要在您的数据库中添加此功能。

请尝试

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 中的值始终仅由逗号 , 符号(无空格)分隔时,上述解决方案才有效。

希望对您有所帮助。