How to properly use XML parameter for Update procedure in SQL Server

后端 未结 2 857
暖寄归人
暖寄归人 2021-01-15 22:08

I am pretty new to XML and am looking for a way to use XML from an input parameter for the below part of a stored procedure (using SQL Server 2012). The XML is submitted via

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-15 22:54

    var xmlMain = '
                     ' + title + '
                     ' + summary + '
                     ' + post + '
                     ' + departmentID + '
                   ';
    

    I suggest you use an XmlDocument to build the desired XML in your code rather than string concatenation. This will properly handle entity references that will otherwise break the XML parser. For example, a title value of "Travel & Expenses" will be invalid as element text. Using XML methods will replace the ampersand with the proper entity reference.

    One method to update the table with the XML element values is with the UPDATE...FROM syntax. This assumes @PostID is passed as a separate parameter.

    CREATE PROC dbo.usp_UpdateRC_PostsFromXml
          @postID int
        , @xmlMain XML
    AS
    
    UPDATE  p
    SET     title = [Cols].value('(title)[1]', 'nvarchar(100)'),
            summary = [Cols].value('(summary)[1]', 'nvarchar(500)'),
            post = [Cols].value('(post)[1]', 'nvarchar(max)'),
            departmentID = [Cols].value('(departmentID)[1]', 'int')
    FROM RC_Posts AS p
    CROSS APPLY @xmlMain.nodes('/root') AS [Xml_Tab]([Cols])
    WHERE   postID = @postID;
    GO
    

提交回复
热议问题