1

次のような 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データ型をあまり使用したことがありません。

4

1 に答える 1

1

次のようなものを使用してみることができます。

;WITH XMLNAMESPACES('http://myurl.com/services/' AS p)
SELECT
    NotificationDate = Notif.value('(p:NotificationDate)[1]', 'DATE'),
    CodeCount = Notif.value('count(p:Scopes/p:NotificationScope/p:Code)', 'int')
FROM
    @xmlvar.nodes('/p:Root/p:Notifications/p:Notification') AS Tbl(Notif)

次の出力が得られます。

ここに画像の説明を入力

于 2012-10-16T06:14:08.720 に答える