declare @xml xml='<plan>
<prescriptions id="1">
<prescription>
<name>ABC</name>
<frequency>Daily</frequency>
<dailyfrequency>
<morning>2</morning>
<afternoon></afternoon>
<night>1</night>
</dailyfrequency>
<dayfrequency></dayfrequency>
</prescription>
<prescription>
<name>EDF</name>
<frequency>Daily</frequency>
<dailyfrequency>
<morning>5</morning>
<afternoon>5</afternoon>
<night>1</night>
</dailyfrequency>
<dayfrequency></dayfrequency>
</prescription>
<prescription>
<name>YTER</name>
<frequency>Weekly</frequency>
<dailyfrequency>
<morning>5</morning>
<afternoon>5</afternoon>
<night>1</night>
</dailyfrequency>
<dayfrequency>Monday,Tuesday,Wednesday</dayfrequency>
</prescription>
</prescriptions>
<prescriptions id="2">
<prescription>
<name>YTRE</name>
<frequency>Daily</frequency>
<dailyfrequency>
<morning>2</morning>
<afternoon></afternoon>
<night>1</night>
</dailyfrequency>
<dayfrequency></dayfrequency>
</prescription>
</prescriptions>
</plan>'
我们可以像下面这样查询,用多个分隔符隔离每个元素,以产生相同的列。
SELECT STUFF(
(
SELECT '!' + STUFF(p.query(N'for $n in .//*[local-name()!="dailyfrequency"]
return <a>{concat("$",($n/text())[1])}</a>'
).value(N'.',N'nvarchar(max)'),1,1,'')
FROM @xml.nodes(N'/plan/prescriptions/prescription') AS A(p)
FOR XML PATH(''),TYPE).value(N'.',N'nvarchar(max)'),1,1,'')
结果:
ABC$Daily$2$$1$!EDF$Daily$5$5$1$!YTER$Weekly$5$5$1$Monday,Tuesday,Wednesday!YTRE$Daily$2$$1$
但问题是这将把所有标签组合在一个列下。当我们看xml时它有2个主要的分区处方id = 1和prescritpion id = 2.所以我们的最终结果将是这样的
结果:
ABC$Daily$2$$1$!EDF$Daily$5$5$1$!YTER$Weekly$5$5$1$Monday,Tuesday,Wednesday
YTRE$Daily$2$$1$
我认为我们必须为每个&lt; 处方&gt;切碎Xml然后必须计算这个
有人可以在这里解决这个问题
提前致谢,Jayendran
答案 0 :(得分:1)
更改您的查询:
SELECT STUFF(
(
SELECT '!' + STUFF(p.query(N'for $n in .//*[local-name()!="dailyfrequency"]
return <a>{concat("$",($n/text())[1])}</a>'
).value(N'.',N'nvarchar(max)'),1,1,'')
FROM p.nodes(N'prescription') AS A(p)
FOR XML PATH(''),TYPE).value(N'.',N'nvarchar(max)'),1,1,'')
FROM @xml.nodes(N'/plan/prescriptions') AS A(p);
首先,我们为不同的处方创建一个派生表,其次我们分别使用每个处方的前代码。