次のような XML 列があります。
DECLARE @str AS VARCHAR(8000)
SET @str = '<Root xmlns="http://myurl.com/services/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Notifications>
<Notification>
<NotificationDate>2012-08-16</NotificationDate>
<Scopes>
<NotificationScope>
<Code>a</Code>
</NotificationScope>
<NotificationScope>
<Code>b</Code>
</NotificationScope>
</Scopes>
</Notification>
<Notification>
<NotificationDate>2012-08-20</NotificationDate>
<Scopes>
<NotificationScope>
<Code>a</Code>
</NotificationScope>
</Scopes>
</Notification>
</Notifications></Root>'
通知ごとに NotificationScope 要素の数を取得できるようにしたいと考えています。たとえば、次のようなものを探しています。
Notification Date Count
2012-08-16 2
2012-08-20 1
実際、このデータはデータベースの列から取得されるので、実際には、Count が 1 より大きい ANY Notification Date を持つレコードを返すことにのみ関心があります。
これまでのところ、私が思いついたのは次のことだけですが、それは私に ; の数を与えるだけです。
declare @xmlvar XML;
set @xmlvar = (SELECT cast(@str AS XML))
;WITH XMLNAMESPACES('http://myurl.com/services/' AS p)
SELECT * FROM (
select @xmlvar.value('count(/p:Root/p:Notifications/p:Notification/p:Scopes/p:NotificationScope)', 'INT') AS 'NotificationScopeCount',
@xmlvar.value('count(/p:Root/p:Notifications/p:Notification/p:NotificationDate)', 'INT') AS 'NotificationDateCount'
) a WHERE NotificationScopeCount > NotificationDateCount
しかし、理想的には、関連する日付も取得できるようにしたいと考えています。これが恐ろしい方法である場合はご容赦ください。SQLでXMLデータ型をあまり使用したことがありません。