How to dynamically change the index value with SQL DML

前端 未结 2 1154
情歌与酒
情歌与酒 2021-01-15 03:18

I am a beginner in XML with SQL. How can I specify index within an insert statement as below. The following statement gives throws exception with invalid path to update.

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-15 03:54

    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 Test1 
                         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

提交回复
热议问题