How to dynamically change the index value with SQL DML

前端 未结 2 1155
情歌与酒
情歌与酒 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 <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

    0 讨论(0)
  • 2021-01-15 04:17

    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

    0 讨论(0)
提交回复
热议问题