以下脚本可用于显示我遇到的问题的示例。该脚本将返回错误“没有名为'this'的元素。”
如果我更改了@XML变量的声明,因此它是无类型的XML(用DECLARE @XML XML(Test)
替换行DECLARE @XML XML
),我不会收到错误,而是获得预期的结果。< / p>
为什么在使用Schema集合时会出现错误?如何避免错误?我想用正确类型的xml填充表列,但是我无法将数据从列中取出。
IF EXISTS (SELECT name FROM sys.xml_schema_collections WHERE name = 'test') DROP XML SCHEMA COLLECTION Test
CREATE XML SCHEMA COLLECTION Test AS
'<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:t="http://tempuri.org/this.xsd"
targetNamespace="http://tempuri.org/this.xsd"
elementFormDefault="qualified">
<xsd:element name ="this">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="What" minOccurs="1" maxOccurs="1" >
<xsd:simpleType>
<xsd:restriction base ="xsd:string">
<xsd:enumeration value ="01."/>
<xsd:enumeration value ="02."/>
<xsd:enumeration value ="03."/>
<xsd:enumeration value ="04."/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="When" minOccurs="1" maxOccurs="1" >
<xsd:simpleType>
<xsd:restriction base ="xsd:string">
<xsd:enumeration value ="01."/>
<xsd:enumeration value ="02."/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="Outcome" minOccurs="1" maxOccurs="1" >
<xsd:simpleType>
<xsd:restriction base ="xsd:string">
<xsd:enumeration value ="one"/>
<xsd:enumeration value ="two"/>
<xsd:enumeration value ="whatever"/>
<xsd:enumeration value =""/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>'
GO
DECLARE @XML XML(Test)
SET @XML =
'<this xmlns="http://tempuri.org/this.xsd">
<What>02.</What>
<When>01.</When>
<Outcome></Outcome>
</this>'
SELECT @XML
SELECT
Field.value('What[1]','VARCHAR(100)')
FROM @Xml.nodes('/this') AS this(Field)
答案 0 :(得分:3)
问题是您的名称空间声明:<this xmlns="http://tempuri.org/this.xsd">
。该XML片段中的所有内容都属于命名空间http://tempuri.org/this.xsd
。您的查询使用了this
和What
的非限定名称。请改用:
;WITH XMLNAMESPACES (
'http://tempuri.org/this.xsd' as t
)
SELECT
Field.value('t:What[1]','VARCHAR(100)')
FROM @Xml.nodes('/t:this') AS this(Field)