I have an XML column that looks something like the following;
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>'
I want to be able to get a count of the number of NotificationScope Elements per notification. So for example, I am looking for something like;
Notification Date Count
2012-08-16 2
2012-08-20 1
In fact, as in reality as this data is obtained from a database column, I am really only interested in returning those records that have ANY Notification Date with a Count that is greater than 1.
So far, all I’ve managed to come up with is the following, but that just gives me a count of ;
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
but ideally, I’d like to be able to get the associated date also. Please forgive me if this is a horrible way of going about this, I haven’t used XML datatypes much before in SQL.
You can try to use something like this:
Gives me an output of: