Wednesday, March 28, 2012

Iteration through all XML nodes

Hi!
I have one simple problem:
DECLARE @.USERS xml
DECLARE @.USERID bigint
SET @.USERS=
'<users>
<user id="1" />
<user id="2" />
<user id="3" />
<user id="4" />
..
</users>'
Now I'd like to iterate throught all nodes <user>, for each node store
value
/users/user/@.id into @.USERID, and execute procedure sp_DoSomething
@.USERID.
How to do it? Thanks in advance!
Regards,
ReplyOkay, I did it like this:
DECLARE @.CNT int
SET @.CNT = @.USERS.value('count(/users/user)','int')
DECLARE CUR CURSOR FOR
SELECT nref.value('@.id', 'int') item
FROM @.users.nodes('/users/user') AS R(nref)
OPEN CUR
FETCH NEXT FROM CUR INTO @.USERID
WHILE @.@.FETCH_STATUS = 0
BEGIN
EXEC SP_DoSomething @.USERID
FETCH NEXT FROM CUR INTO @.USERID
END
CLOSE CUR
DEALLOCATE CUR

No comments:

Post a Comment