SQL Server 2008+ has easier ways to insert multiple rows into a single statement. For example, this syntax is valid:
INSERT dbo.table(col1, col2) VALUES (1, 2), (2, 3), (3, 4);
The above inserts three lines. In older versions, you can do a few more detailed things, such as:
INSERT dbo.table(col1, col2) SELECT 1, 2 UNION ALL SELECT 2, 3 UNION ALL SELECT 3, 4;
Of course, your ExecuteNonQuery does not have to be a single command, you can pass this as a single line, and it will still work:
INSERT dbo.table(col1, col2) VALUES(1, 2); INSERT dbo.table(col1, col2) VALUES(2, 3); INSERT dbo.table(col1, col2) VALUES(3, 4);
If you want to do this in a stored procedure, you can easily split into multi-valued parameters, for example, if you pass the following line:
1,2;2,3;3,4
You can process these values ββwith a function similar to the one I posted here:
Separate value pairs and create a table using UDF
So your procedure might look like this:
CREATE PROCEDURE dbo.AddOrderLineItems @LineItems VARCHAR(MAX) AS BEGIN SET NOCOUNT ON; INSERT dbo.OrderItems(Product, Quantity) SELECT Product, Quantity FROM dbo.MultiSplit(@LineItems); END GO
And you would call it using the C # equivalent:
EXEC dbo.AddOrderLineItems @LineItems = '1,2;2,3;3,4';
Or you can use the table parameters suggested by Alexey. Quick example:
CREATE TYPE OrderLineItem AS TABLE ( Product INT, Quantity INT );
Then you can create a procedure:
CREATE PROCEDURE dbo.AddOrderLineItems @LineItems OrderLineItem READONLY -- other parameters AS BEGIN SET NOCOUNT ON; INSERT dbo.OrderItems(Product, Quantity) SELECT Product, Quantity FROM @LineItems; END GO
Then create an equivalent TVP in C # code (I'm not the guy you want to make, you can see an example here ).
However, there are some reservations, please look at this question:
Creating a generic type to use table value as a parameter