[英]How to xQuery an element that is a list of xs:date that can be empty?
我有一个带有xs:date
属性的架构,该架构以可能包含日期或为空的方式定义。
但是,当我尝试查询此元素时,出现错误
"XQuery [value()]: 'value()' requires a singleton (or empty sequence), found operand of type 'xs:date *'"
有什么建议么?
重现步骤
create xml schema collection dbo.[test] AS
N'<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="PACKAGE" >
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="CUSTOMER">
<xs:complexType>
<xs:sequence>
<xs:element name="BIRTHDAY" >
<xs:annotation>
<xs:documentation>Date of Birth</xs:documentation>
</xs:annotation>
<xs:simpleType>
<xs:restriction>
<xs:simpleType>
<xs:list itemType="xs:date" />
</xs:simpleType>
<xs:minLength value="0" />
<xs:maxLength value="1" />
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>';
go
declare @xml xml(dbo.[test]);
set @xml =
'<PACKAGE>
<CUSTOMER>
<BIRTHDAY></BIRTHDAY>
</CUSTOMER>
<CUSTOMER>
<BIRTHDAY>2010-01-01</BIRTHDAY>
</CUSTOMER>
</PACKAGE>'
select
BIRTHDAY = t.cust.value('(BIRTHDAY)[1]', 'date')
FROM @xml.nodes('/PACKAGE/CUSTOMER') as t(cust)
go
drop xml schema collection dbo.[test]
您可以使用数据功能(XQuery)
select
BIRTHDAY = t.cust.value('data(BIRTHDAY)[1]', 'date')
FROM @xml.nodes('/PACKAGE/CUSTOMER') as t(cust)
SQL Server中的函数value()
需要一个值,并且BIRTHDAY
被定义为日期列表。 (BIRTHDAY)[1]
将为您提供第一个日期列表 。 data(BIRTHDAY)[1]
将为您提供BIRTHDAY
存储的日期列表中的第一个日期。
得到它了! (其他方式)
select
BIRTHDAY = nullif(t.cust.query('BIRTHDAY').value('(BIRTHDAY)[1]', 'date'), '1900-01-01')
from @xml.nodes('/PACKAGE/CUSTOMER') as t(cust)
结果:
BIRTHDAY
----------
NULL
2010-01-01
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.