从sql:variable使用Xpath删除Xquery

时间:2016-11-18 09:05:21

标签: sql-server xml xpath xquery-sql

我在VARCHAR(MAX)变量中使用Xpath从XML中删除,但是XML.modify('delete '+@MyXpath)会出错,

  

XML数据类型方法的参数1"修改"必须是一个字符串   文字。

DECLARE @myXML XML,
        @MyXpath VARCHAR(MAX)

-- Processing of Xpaths for components needed to remove 
-- Adding those in @XpathsToRemove     

SELECT TOP(1) @MyXpath = [XPATH]
FROM @XpathsToRemove

SET @myXML.modify('delete '+@MyXpath)

有没有办法在@MyXpath变量中删除那些带有Xpath的组件?

- 编辑示例XML

DECLARE @myXML XML ='<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Dont forget me this weekend!</body>
</note>'
      ,@MyXpath VARCHAR(MAX) = '//note/from'

      -- There are many Xpaths and dynamically generated with some processing so I don't want to hardcode Xpath there
      SET @myXML.modify('delete '+@MyXpath)

       --This doesn't works too
      -- SET @myXML.modify('delete "sql:variable("MyXPath")"')
      SELECT @myXML

1 个答案:

答案 0 :(得分:0)

谢谢大家,我得到EXEC的解决方案来生成动态查询。 以下链接解决了我的问题,

How to using for loop using XQuery to delete xml nodes [duplicate]

解,

DECLARE @str nvarchar(MAX)
SET @str = 'SET @MyXML.modify('+char(39)+'delete '+@MyXPath+'/*'+char(39)+'); '
EXEC sp_executesql  @str, N'@MyXML xml output', @MyXML output