简体   繁体   中英

Insert multiple parent child records into SQL Server 2008 in a stored procedure

I have two tables Portfolio and Trades . Once the portfolio data has been inserted, using that Id, I insert the trades details into the Trades table.

I will get multiple portfolio in a single request, for example, if I get two portfolio P1 and P2, I need to insert two records into the Portfolio table, and the corresponding trades details into the Trades table once for every portfolio.

How to pass this entire data in a single stored procedure call in order to maintain the transaction?

Starting with sql server 2008, you can use table valued parameter s to pass a table structured data in a single call to a stored procedure.
However, Not every client supports this. It's easy to use with .Net, but I doubt it's possible with VBScript, for instance.

In order to use a table valued parameter you must first create a user defined table type:

CREATE TYPE UDT_Portfolio As Table
(
    Portfolio_Id int,
    Portfolio_Name varchar(10),
    .....
) 

in your case, since you want to pass 2 tables, you need 2 types:

CREATE TYPE UDT_Trades As Table
(
    Trade_Id int,
    Trade_Portfolio_Id int,
    Trade_Name varchar(10),
    ....
)

Now, to use them in a stored procedure is very easy:

CREATE PROCEDURE stp_InsertPortfoliosAndTrades
(
     @Portfolio UDT_Portfolio readonly, -- Note: Readonly is a must
     @Trade UDT_Trades readonly
)
AS

-- stored procedure logic here

Note #1: : Table valued parameters are readonly. meaning you can't use update, insert or delete statements on them. However, you can declare a table valued variable inside a stored procedure and use insert, update, and deletes on that.

Note #2: If your portfolio id is an identity column, then when inserting the data to the portfolio table you will need to use an output clause to get the new id values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM