我已将对象序列化为SQL Server 2008数据库中的XML列。
xml看起来像这样:
<SimpleUserData xmlns="http://schemas.datacontract.org/2004/07/MyProject.CustomFx.Web" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/" z:Id="1" z:Type="MyProject.CustomFx.Web.SimpleUserData" z:Assembly="MyProject.CustomFx.Web, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
<BatchDescription z:Id="2">I want this value</BatchDescription>
<BatchID>9c437c08-0f28-4c77-9a50-49a7a4e8930a</BatchID>
<BatchTemplateID>And this value too</BatchTemplateID>
</SimpleUserData>
我想编写一个查询,显示元素BatchDescription
和BatchTemplateID
中的值。
我现在的查询如下所示:
declare @xmlobj as xml = '<SimpleUserData xmlns="http://schemas.datacontract.org/2004/07/MyProject.CustomFx.Web" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/" z:Id="1" z:Type="MyProject.CustomFx.Web.SimpleUserData" z:Assembly="MyProject.CustomFx.Web, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
<BatchDescription z:Id="2">I want this value</BatchDescription>
<BatchID>9c437c08-0f28-4c77-9a50-49a7a4e8930a</BatchID>
<BatchTemplateID>And this value too</BatchTemplateID>
</SimpleUserData>';
select
@xmlobj.query('
declare namespace x="http://schemas.datacontract.org/2004/07/MyProject.CustomFx.Web";
(/x:SimpleUserData[1]/x:BatchDescription[1])
') as value1
,@xmlobj.query('
declare namespace x="http://schemas.datacontract.org/2004/07/MyProject.CustomFx.Web";
(/x:SimpleUserData[1]/x:BatchTemplateID[1])
') as value2;
这很接近;它返回整个标记和其中的值。
我怎样才能得到这些值(即“我想要这个值”和“和这个值一样”)
答案 0 :(得分:3)
.query将始终返回数据类型XML。
要查询值,您应使用“.value”,并将数据类型指定为第二个参数。
请改用:
declare @xmlobj as xml = '<SimpleUserData xmlns="http://schemas.datacontract.org/2004/07/MyProject.CustomFx.Web" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/" z:Id="1" z:Type="MyProject.CustomFx.Web.SimpleUserData" z:Assembly="MyProject.CustomFx.Web, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
<BatchDescription z:Id="2">I want this value</BatchDescription>
<BatchID>9c437c08-0f28-4c77-9a50-49a7a4e8930a</BatchID>
<BatchTemplateID>And this value too</BatchTemplateID>
</SimpleUserData>';
WITH XMLNAMESPACES('http://schemas.datacontract.org/2004/07/MyProject.CustomFx.Web' as x)
select
@xmlobj.value('(/x:SimpleUserData[1]/x:BatchDescription[1])','nvarchar(max)') as value1
,@xmlobj.value('(/x:SimpleUserData[1]/x:BatchTemplateID[1])','nvarchar(max)') as value2;