Сделайте UNION
вместо CASE
и используйте @
для создания атрибута.
SELECT
t1.Code,
(SELECT
(SELECT CodeName as '@Name'
FROM (
SELECT t2.CodeName
FROM Table2 t2
WHERE t2.Id = t4.Id AND
t1.Type = 5
UNION ALL
SELECT t3.CodeName
FROM Table3 t3
WHERE t3.Id = t4.Id AND
t1.Type <> 5
) AS T
FOR XML PATH('Code'), TYPE)
FROM Table4 t4
WHERE t4.Id = t1.Id
FOR XML PATH('CodeNames'), TYPE)
FROM Table1 t1
FOR XML RAW ('Table1Child'), TYPE, ROOT('Table1Root')
Похоже, вам на самом деле не нужно использовать Table4
.
SELECT
t1.Code,
(SELECT CodeName as '@Name'
FROM (
SELECT t2.CodeName
FROM Table2 t2
WHERE t2.Id = t1.Id AND
t1.Type = 5
UNION ALL
SELECT t3.CodeName
FROM Table3 t3
WHERE t3.Id = t1.Id AND
t1.Type <> 5
) AS T
FOR XML PATH('Code'), ROOT('CodeNames'), TYPE)
FROM Table1 t1
FOR XML RAW ('Table1Child'), TYPE, ROOT('Table1Root')