开发者

What is the best way to pass a DataTable into a Stored Procedure?

开发者 https://www.devze.com 2023-01-26 20:51 出处:网络
I need to pass a DataTable into a stored procedure in MS SQL 2008 to insert multiple rows into a table at the same time. I have come across methods that use XML documents for thi开发者_开发知识库s and

I need to pass a DataTable into a stored procedure in MS SQL 2008 to insert multiple rows into a table at the same time. I have come across methods that use XML documents for thi开发者_开发知识库s and even passing lists as image data.

What is the best way to accomplish this?

Give code samples and/or references if possible.


Have a look at Table-Valued Parameters and SQL Server 2008: Table Valued Parameters


Table-Valued Parameters are a good option, personally I prefer to create a temp table in the calling stored procedure and read from the temp table in the called procedure.

So in code that would be:

CREATE PROC DoStuff
AS BEGIN
    CREATE TABLE #tobeinserted (Data1 INT, Data2 INT...)
    EXEC InsertRows
END

CREATE PROC InsertRows
AS BEGIN
    INSERT INTO Table1 SELECT * FROM #tobeinserted
END

This works reliably, because temporary tables have a lifetime until the stored procedure in which they are created exits. An advantage to this method is that temporary tables, unlike table valued parameters, can have (clustered) indexes defined, so lookups in these tables can be very fast. A disadvantage is that you cannot run two instances of the SP simultaneously.

0

精彩评论

暂无评论...
验证码 换一张
取 消