sql server - Filter duplicate nodes before inserting into XML field -
i using xml field store suggestions books in format:
<books> <book id="1" score="2" /> <book id="2" score="3" /> </books> at point need add suggestions xml. done these statements:
declare @books xml; select @books = suggestions.query('//books/book') user userid = @userid update user set suggestions.modify('insert sql:variable("@books") first (//books)[1]') userid = @userid how can make sure i'm not inserting nodes exist (based on id attribute only).
one way achieve creating new xml variable new values.
data:
create table #user(userid int, suggestions xml, name varchar(100)); insert #user(userid, suggestions, name) values (1, '<books> <book id="1" score="2" /> <book id="2" score="3" /> </books>' ,'john'); declare @books xml =n'<book id="1" score="2" /> <book id="2" score="3" /> <book id="3" score="4" /> <book id="4" score="4" />'; query:
declare @userid int = 1; ,@only_new_books xml; ;with books ( select id = s.c.value('@id', 'int'), score = s.c.value('@score', 'int') @books.nodes('/book') s(c) ), suggestions ( select userid, id = s.c.value('@id', 'int'), score = s.c.value('@score', 'int') #user cross apply suggestions.nodes('//books/book') s(c) userid = @userid ) select @only_new_books = (select b.id '@id', b.score '@score' books b left join suggestions s on b.id = s.id s.id null xml path('book'),type ); update #user set suggestions.modify('insert sql:variable("@only_new_books") first (//books)[1]') userid = @userid; select * #user; output:
╔════════╦══════════════════════════════════════╦══════╗ ║ userid ║ suggestions ║ name ║ ╠════════╬══════════════════════════════════════╬══════╣ ║ 1 ║ <books> ║ john ║ ║ ║ <book id="3" score="4" /> ║ ║ ║ ║ <book id="4" score="4" /> ║ ║ ║ ║ <book id="1" score="2" /> ║ ║ ║ ║ <book id="2" score="3" /> ║ ║ ║ ║ </books> ║ ║ ╚════════╩══════════════════════════════════════╩══════╝
Comments
Post a Comment