我在指定格式中创建数据时遇到问题。 我需要这样的结果:
<Units>
<Unit>0111024626914331</Unit>
<Unit>0111024626914348</Unit>
<Unit>00273129808000257576</Unit>
<Unit>00273129808000257590</Unit>
</Units>
我的陈述:
SELECT distinct PA.KOD_KRESKOWY as UNIT
FROM LISTY_LINIOWE_POZ_P AS LLPP INNER JOIN PACZKI AS PA on PA.ID_PACZKI = LLPP.PACZKI_ID
WHERE LISTY_LINIOWE_ID = 616665
FOR XML PATH ('UNITS'),type
给我结果:
<Units>
<UNIT>P/000005/2018+1/3</UNIT>
</UNITS>
<UNITS>
<UNIT>P/000005/2018+2/3</UNIT>
</UNITS>
<UNITS>
<UNIT>P/000005/2018+3/3</UNIT
</Units>
我在表格的一列中有单位。
答案 0 :(得分:3)
虽然您已经得到了答案,但是值得了解FOR XML PATH()
中的命名级别。
SELECT PA.KOD_KRESKOWY as [*]
FROM LISTY_LINIOWE_POZ_P AS LLPP INNER JOIN PACZKI AS PA on PA.ID_PACZKI = LLPP.PACZKI_ID
WHERE LISTY_LINIOWE_ID = 616665
GROUP BY PA.KOD_KRESKOWY
FOR XML PATH ('UNIT'),ROOT('UNITS'),type;
GROUP BY
优于DISTINCT
<UNIT>
更像是行标记。只有一列,它也适用于空PATH('')
。 试试这个:
DECLARE @mockup TABLE(SomeValue VARCHAR(100), SomeNumber INT);
INSERT INTO @mockup
VALUES('blah',1)
,('blub',2);
- 标准
SELECT SomeValue
,SomeNumber
FROM @mockup
FOR XML PATH('RowTag'),ROOT('RootTag')
<RootTag>
<RowTag>
<SomeValue>blah</SomeValue>
<SomeNumber>1</SomeNumber>
</RowTag>
<RowTag>
<SomeValue>blub</SomeValue>
<SomeNumber>2</SomeNumber>
</RowTag>
</RootTag>
- 第一列将是text()
下方的<RowTag>
节点
SELECT SomeValue AS [*]
,SomeNumber
FROM @mockup
FOR XML PATH('RowTag'),ROOT('RootTag')
<RootTag>
<RowTag>blah<SomeNumber>1</SomeNumber></RowTag>
<RowTag>blub<SomeNumber>2</SomeNumber></RowTag>
</RootTag>
- 两个列都没有名字,有趣的效果......
SELECT SomeValue AS [*]
,SomeNumber AS [*]
FROM @mockup
FOR XML PATH('RowTag'),ROOT('RootTag')
<RootTag>
<RowTag>blah1</RowTag>
<RowTag>blub2</RowTag>
</RootTag>
- 两列的相同别名也可能是意外的
SELECT SomeValue AS SameAlias
,SomeNumber AS SameAlias
FROM @mockup
FOR XML PATH('RowTag'),ROOT('RootTag')
<RootTag>
<RowTag>
<SameAlias>blah1</SameAlias>
</RowTag>
<RowTag>
<SameAlias>blub2</SameAlias>
</RowTag>
</RootTag>
- 空<RowTag>
SELECT SomeValue
,SomeNumber
FROM @mockup
FOR XML PATH(''),ROOT('RootTag')
<RootTag>
<SomeValue>blah</SomeValue>
<SomeNumber>1</SomeNumber>
<SomeValue>blub</SomeValue>
<SomeNumber>2</SomeNumber>
</RootTag>
- 没有<RootTag>
SELECT SomeValue
,SomeNumber
FROM @mockup
FOR XML PATH('RowTag')
<RowTag>
<SomeValue>blah</SomeValue>
<SomeNumber>1</SomeNumber>
</RowTag>
<RowTag>
<SomeValue>blub</SomeValue>
<SomeNumber>2</SomeNumber>
</RowTag>
- 没有<RowTag>
而没有<RootTag>
SELECT SomeValue
,SomeNumber
FROM @mockup
FOR XML PATH('')
<SomeValue>blah</SomeValue>
<SomeNumber>1</SomeNumber>
<SomeValue>blub</SomeValue>
<SomeNumber>2</SomeNumber>
- 根本没有标签
SELECT SomeValue AS [*]
,SomeNumber AS [*]
FROM @mockup
FOR XML PATH('')
blah1blub2 <-- but this is still native XML-type!
重要的是要知道,因为有时你可以实现不可能的:-D
如果需要,您也可以使用更深的路径(AS [Level1/Level2]
)和/或使用属性(AS [Level1/Level2/@AnAttribute]
)对此进行测试。玩得开心!