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