Should you make multiple insert calls or pass XML?

前端 未结 4 494
一整个雨季
一整个雨季 2020-12-04 02:24

I have an account creation process and basically when the user signs up, I have to make entries in mutliple tables namely User, Profile, Addresses. There will be 1 entry in

4条回答
  •  孤街浪徒
    2020-12-04 03:01

    For example assuming your xml as below

    
    
     
    
    
     
    
    

    this would be your stored procedure

    INSERT INTO Users (UserName) SELECT(UserName) FROM OPENXML(@idoc,'StoredProcedure/User',2)
    WITH ( UserName NVARCHAR(256))
    

    where this would provide idoc variable value and @doc is the input to the stored procedure

    DECLARE @idoc INT
    
    --Create an internal representation of the XML document.        
    EXEC sp_xml_preparedocument @idoc OUTPUT, @doc
    

    using similar technique you would run 3 inserts in single stored procedure. Note that it is single call to database and multiple address elements will be inserted in single call to this stored procedure.

    Update

    just not to mislead you here is a complete stored procedure for you do understand what you are going to do

    USE [DBNAME]
    GO
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER OFF
    GO  
    CREATE PROCEDURE [dbo].[procedure_name]
        @doc [ntext]
    WITH EXECUTE AS CALLER
    AS
    DECLARE @idoc INT  
    DECLARE @RowCount INT
    SET @ErrorProfile = 0
    
    --Create an internal representation of the XML document.
    EXEC sp_xml_preparedocument @idoc OUTPUT, @doc
    
    BEGIN TRANSACTION
    
    INSERT INTO Users (UserName)
    SELECT UserName FROM OPENXML(@idoc,'StoredProcedure/User',2)
    WITH ( UserName NVARCHAR(256) )
    
    -- Insert Address
    
    -- Insert Profile
    
    
    SELECT @ErrorProfile = @@Error                              
    
    IF @ErrorProfile = 0
        BEGIN
                COMMIT TRAN
        END
    ELSE
        BEGIN
                ROLLBACK TRAN
        END
    
    EXEC sp_xml_removedocument @idoc   
    

提交回复
热议问题