SQL Server 2014 相当于 mysql 的 find_in_set()

SQL Server 2014 equivalent to mysql's find_in_set()

我正在使用具有位置 table 的数据库,例如:

locationID | locationHierarchy
1          | 0
2          | 1
3          | 1,2
4          | 1
5          | 1,4
6          | 1,4,5

这样一棵树

1
--2
----3
--4
----5
------6

其中 locationHierarchy 是其所有祖先的 locationID 的 csv 字符串(想想层次结构树)。这使得在给定起始 locationID 的情况下朝着树的顶部工作时可以轻松确定层次结构。

现在我需要编写代码以从祖先开始并递归地查找所有后代。 MySQL 有一个名为 'find_in_set' 的函数,它可以轻松解析 csv 字符串以查找值。这很好,因为我可以只说 "find in set the value 4" 这将给出所有 locationID 为 4(包括 4 本身)的后代的位置。

不幸的是,这是在 SQL Server 2014 上开发的,它没有这样的功能。 CSV 字符串是一个可变长度(允许几乎无限的级别),我需要一种方法来找到一个位置的所有祖先。

我在 Internet 上发现的很多将 find_in_set 函数模仿成 SQL 服务器假定固定深度的层次结构,例如最多 4 级)这不适用于我.

有没有人有存储过程或任何我可以集成到查询中的东西?我真的不想从这个 table 中提取所有记录来使用代码单独解析 CSV 字符串。

我想在 locationHierarchy 字符串中搜索 locationID% 或 %,{locationid},% 会起作用,但速度很慢。

我认为您想要 like -- 在任一数据库中。像这样:

select l.*
from locations l
where l.locationHierarchy like @LocationHierarchy + ',%';

如果您想要包括原始位置,那么一种方法是:

select l.*
from locations l
where l.locationHierarchy + ',' like @LocationHierarchy + ',%';

我还应该注意到 SQL 服务器对递归查询有适当的支持,因此除了层次结构树(这仍然是一个非常合理的解决方案)之外,它还有其他层次结构选项。

终于对我有用了..

SELECT * FROM locations WHERE locationHierarchy like CONCAT(@param,',%%')    OR
                                    o.unitnumber like CONCAT('%%,',@param,',%%') OR
                                    o.unitnumber like CONCAT('%%,',@param)