如何选择前5个使用XML数据类型读取存储在SQL Server中的XML文档?

时间:2014-04-07 13:31:56

标签: c# asp.net xml sql-server-2008

我需要使用XML数据类型读取存储在SQL Server 2008 R2中的XML文档。

其实我是新手。我使用的是SQL Server 2008和ASP.NET 4.0。我在XML端以XML格式存储数据表(.NET)。

这是在表列中存储在SQL Server中的XML的示例。就像我有超过10列,这里我需要选择最后插入的4列<Data />

"really a nice solution file" 

从xml文件下面可以请你帮忙

提前致谢

<Section xml:space="aligned" Paste="False" xmlns="http://schemas.microsoft.com">
<Para FontSize="11" FontWeight="Normal" FontStyle="Normal" TextAlignment="Left">
<Data Text="really a nice solution, but i have an other issue that  want to create its xml file" />
</Para>
</Section>

<Section xml:space="aligned" Paste="False" xmlns="http://schemas.microsoft.com">
<Para FontSize="11" FontWeight="Normal" FontStyle="Normal" TextAlignment="Left">
<Data Text="really a nice solution file" />
</Para>
</Section> 

这是我的表结构

ID       Name         XMLContent                                  CreatedDate                   |       Modified
--------|------------|------------------|------------------------|-----------------------------------------
1       | CATEGORYID |<Section xml:space="aligned" Paste="False".|    |2011-04-05 12:28:15.030  |      
2       |    114     |<Section xml:space="aligned" Paste="False".|2011-04-05 12:28:15.030       |       

我需要得到像

这样的答案
1   |really a nice solution, but i have an other issue that  want to create its xml file| 
2   |really a nice solution, |  

1 个答案:

答案 0 :(得分:1)

假设您有一个包含IDXmlData列的表格(根据需要进行调整 - 您应该在提出这些问题时发布您的表格结构!),您可以使用以下内容:< / p>

DECLARE @xmltbl TABLE (ID INT, XmlData XML)

INSERT INTO @xmltbl(ID, XmlData) 
VALUES(1, '<Section xmlns="http://schemas.microsoft.com">
<Para FontSize="11" FontWeight="Normal" FontStyle="Normal" TextAlignment="Left">
<Data Text="really a nice solution, but i have an other issue that  want to create its xml file" /></Para></Section>'), 
(2, '<Section xmlns="http://schemas.microsoft.com">
<Para FontSize="11" FontWeight="Normal" FontStyle="Normal" TextAlignment="Left">
<Data Text="really a nice solution file" /></Para></Section> ');

;WITH XMLNAMESPACES(DEFAULT 'http://schemas.microsoft.com')
SELECT 
    ID,
    DataText = XmlData.value('(/Section/Para/Data/@Text)[1]', 'varchar(200)')
FROM @xmltbl

我必须从XML中删除xml:space="aligned" Paste="False",因为它会导致错误。

这为您提供了输出:

ID  DataText
1   really a nice solution, but i have an other issue that  want to create its xml file
2   really a nice solution file

如果您需要按日期添加前5行,那么只需将您的选择更改为:

SELECT TOP 5 
    ID, .....
FROM ......
ORDER BY 
    -- order by DateAdded descending - giving you the most recent 5 rows
    DateAdded DESC    

更新:尝试适应您的表格结构 - 您的表格名称仍然未知,因此您需要适应 dbo.YourTableName到您的表格中真的叫!

;WITH XMLNAMESPACES(DEFAULT 'http://schemas.microsoft.com')
SELECT TOP 5
    ID,
    XmlContent.value('(/Section/Para/Data/@Text)[1]', 'varchar(200)')
FROM dbo.YourTableName
ORDER BY CreatedDate DESC