我需要帮助从此XML中检索存储在SQL Server表的列中的数据。我一直在搜索问题库,但找不到与我相符的内容。也许我错过了某种方式。无论如何,这里存储的XML如何:
<ProductStructure>
<Plans>Essential</Plans>
<Plans>Standard</Plans>
<Plans>Silver</Plans>
<Plans>Gold</Plans>
<Plans>Platinum</Plans>
<Plans>Titanium</Plans>
<Destinations>Region A</Destinations>
<Destinations>Region B</Destinations>
<Destinations>Region C</Destinations>
<Destinations>Region D</Destinations>
<InsuredTypes>One Person</InsuredTypes>
<InsuredTypes>Couple</InsuredTypes>
<InsuredTypes>Group</InsuredTypes>
</ProductStructure>
我想选择xml并在SQL中获得如下所示的输出:
|Plans |Essential |
| |Standard |
| |Silver |
| |Gold |
| |Platinum |
| |Titanium |
|---------------+-------------|
|Destinations |Region A |
| |Region B |
| |Region C |
| |Region D |
|---------------+-------------|
|InsuredTypes |One Person |
| |Couple |
| |Group |
很抱歉,如果这个问题看得很糟糕的话。谢谢。
答案 0 :(得分:2)
DECLARE @xml xml = N'<ProductStructure>
<Plans>Essential</Plans>
<Plans>Standard</Plans>
<Plans>Silver</Plans>
<Plans>Gold</Plans>
<Plans>Platinum</Plans>
<Plans>Titanium</Plans>
<Destinations>Region A</Destinations>
<Destinations>Region B</Destinations>
<Destinations>Region C</Destinations>
<Destinations>Region D</Destinations>
<InsuredTypes>One Person</InsuredTypes>
<InsuredTypes>Couple</InsuredTypes>
<InsuredTypes>Group</InsuredTypes>
</ProductStructure>'
SELECT
t.value('local-name(.)','nvarchar(max)'),
t.value('.','nvarchar(max)')
FROM @xml.nodes('ProductStructure/*') AS t(t)
你会得到:
-------------------- --------------------
Plans Essential
Plans Standard
Plans Silver
Plans Gold
Plans Platinum
Plans Titanium
Destinations Region A
Destinations Region B
Destinations Region C
Destinations Region D
InsuredTypes One Person
InsuredTypes Couple
InsuredTypes Group
您可以根据需要对结果进行分组。