Sqlserver
 SQL >> Base de données >  >> RDS >> Sqlserver

Utiliser une variable SQL pour itérer sur des nœuds XML

Votre propre code fonctionnerait avec un seul [1] de plus. La fonction .modify() ne sait pas interpréter [sql:variable(...)]… Ce filtre pourrait renvoyer plusieurs résultats… Remplacez donc ceci par :

DECLARE @xml xml = '<Root> <Contacts> <Contact name="John Doe" type="REG" other="value" /> <Contact name="Jane Doe" type="REG" other="value" /> <Contact name="Jennifer Doe" type="REG" other="value" /> <Contact name="Jane Doe" type="REG" other="value" /> </Contacts> </Root>'; DECLARE @i int = 1 SET @xml.modify('replace value of (/Root/Contacts/Contact)[sql:variable("@i")][1]/@type with "NEW"') SELECT @xml 

Mais je prendrais un autre chemin… Vous pourriez lire l'ensemble dans une table dérivée et reconstruire le XML ainsi :

SELECT ( SELECT c.value('@name','nvarchar(max)') AS [@name] ,'NEW' AS [@type] ,c.value('@other','nvarchar(max)') AS [@other] FROM @xml.nodes('/Root/Contacts/Contact') AS A(c) FOR XML PATH('Contact'),ROOT('Contact'),TYPE ) FOR XML PATH('Root') 

Une autre approche serait FLWOR :

SELECT @xml.query(' for $r in /Root/Contacts return <Root><Contacts> { for $c in /Root/Contacts/Contact return <Contact name="{$c/@name}" type="NEW" other="{$c/@other}"/> } </Contacts></Root> ')