【发布时间】:2017-02-12 08:26:44
【问题描述】:
我的桌子
我的表
+----+-------+---------------+
| Id | Title | DependencyIds |
+----+-------+---------------+
DependentIds 包含类似14;77;120 的值。
MyDependentTable
+--------------+------+
| DependencyId | Name |
+--------------+------+
背景
我必须从MyTable 中选择数据,MyDependentTable 中的每个依赖项都用逗号分隔。
预期输出:
+---------+-------------------------------------+
| Title | Dependencies |
+---------+-------------------------------------+
| Test | ABC, One-two-three, Some Dependency |
+---------+-------------------------------------+
| Example | ABC |
+---------+-------------------------------------+
我的查询
SELECT t.Title,
(SELECT ISNULL((
SELECT DISTINCT
(
SELECT dt.Name + '',
CASE WHEN DependencyIds LIKE '%;%' THEN ', ' ELSE '' END AS [text()]
FROM MyDependentTable dt
WHERE dt.DependencyId IN (SELECT Value FROM dbo.fSplitIds(t.DependencyIds, ';'))
ORDER BY dt.DependencyId
FOR XML PATH('')
)), '')) Dependencies
FROM dbo.MyTable t
问题描述
查询有效,但在有多个依赖项时添加了一个额外的逗号:
+---------+---------------------------------------+
| Title | Dependencies |
+---------+---------------------------------------+
| Test | ABC, One-two-three, Some Dependency, |
+---------+---------------------------------------+
| Example | ABC |
+---------+---------------------------------------+
我无法使用SUBSTRING(ISNULL(...,因为我无法访问字符串的长度,因此我无法设置SUBSTRING 的长度。
有没有可能去掉那个不必要的额外逗号?
【问题讨论】:
标签: sql sql-server tsql sql-server-2014