这可能很简单,但我在这个上面有一个脑屁......
我正在使用FOR XML EXPLICIT
作为子查询的一部分,以便我可以显式定义返回的XML的格式。因此我使用UNION ALL
来定义该格式。
这工作正常,但如果该子查询中没有行,我需要它返回NULL
...此时它返回一个空的根元素:<codes/>
。那是因为我需要定义的第一行。
Here is a sqlfiddlecom with everything below for you to look at.
这是目前的TSQL版本......
SELECT
P.[PROJECTID],
P.[PROJECTNAME],
( SELECT *
FROM (
SELECT
1 AS TAG,
NULL AS PARENT,
NULL AS 'codes!1',
NULL AS 'code!2!!element',
NULL AS 'code!2!split'
UNION ALL
SELECT
2 AS TAG,
1 AS PARENT,
NULL,
C.[CODE],
C.[SPLIT]
FROM [CODES] C
WHERE C.[PROJECTID] = P.[PROJECTID]
) AS [CODEXMLDATA]
FOR XML EXPLICIT
) AS [CODESXML]
FROM [PROJECTS] P
示例数据将与
一致PROJECTS table
PROJECTID PROJECTNAME
1 This
2 That
3 Other
CODES table
PROJECTID CODE SPLIT
1 ABC 45
1 BCD 65
2 CDE 100
结果是......
PROJECTID PROJECTNAME CODESXML
1 This <codes><code split="45">ABC</code><code split="55">BCD</code></codes>
2 That <codes><code split="100">CDE</code></codes>
3 Other <codes/>
我需要的结果是(注意第3行的NULL
)......
PROJECTID PROJECTNAME CODESXML
1 This <codes><code split="45">ABC</code><code split="55">BCD</code></codes>
2 That <codes><code split="100">CDE</code></codes>
3 Other NULL
当没有NULL
时,有人可以告诉我如何让它返回CODES
吗?
答案 0 :(得分:1)
试试此代码
SELECT distinct
P.[PROJECTID],
P.[PROJECTNAME],
case when (p.projectid = c.projectid) then
( SELECT *
FROM (
SELECT
1 AS TAG,
NULL AS PARENT,
NULL AS 'codes!1',
NULL AS 'code!2!!element',
NULL AS 'code!2!split'
UNION ALL
SELECT
2 AS TAG,
1 AS PARENT,
NULL,
C.[CODE],
C.[SPLIT]
FROM [CODES] C
WHERE C.[PROJECTID] = P.[PROJECTID]
) AS [CODEXMLDATA]
FOR XML EXPLICIT
) else null end AS [CODESXML]
FROM [PROJECTS] P
left join [CODES] C on C.[PROJECTID] = P.[PROJECTID]
SQLFiddle:http://sqlfiddle.com/#!3/f8788/7/0