How to dynamically change the index value with SQL DML

試著忘記壹切 提交于 2019-12-01 10:33:46

Did you check out this article. http://technet.microsoft.com/en-us/library/ms175466.aspx

SELECT @myDoc       
set @myDoc.modify('       
insert <BikeFrame>Strong long lasting</BikeFrame> 
after (/Root/ProductDescription/Features/Material)[1]       
')       
SELECT @myDoc;

This assumes that the Material tag exists. Is the path (/xyz/abc) valid?

<Root>
  <ProductDescription ProductID="1" ProductName="Road Bike">
    <Features>
      <Warranty>1 year parts and labor</Warranty>
      <Maintenance>3 year parts and labor extended maintenance is available</Maintenance>
      <Material>Aluminium</Material>
      <BikeFrame>Strong long lasting</BikeFrame>
    </Features>
  </ProductDescription>
</Root>

Also, test you current code with a literal instead of a sql:variable.

Again, please post the xml/code.

Thanks

John

Expression2 in insert (XML DML) has to return a single node. The check is done when the query is parsed the first time and SQL Server can then not evaluate the predicate you are using to figure out if the expression will always return a single node. But if you specify a literal value in the brackets SQL Server knows that only one row will ever be returned.

To solve your issue you need to add a [1] to the end of your expression.

set @xmldata.modify('insert <Test>Test1</Test> 
                     after (/xyz/abc[sql:variable("@index")])[1]')

This will give you the node you want

/xyz/abc[sql:variable("@index")]

and this will tell SQL Server that the expression is guaranteed to return one node.

(/xyz/abc[sql:variable("@index")])[1]

SQL Fiddle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!