Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a big array to a stored procedure

I need to send a several list (about 20000 id's) to a stored procedure, like this:

1391924, 6546510, 7419635, 6599910, 6546888, 1116510, 6546720, ...

I have this data on a List<int>

How can I do to send this list to an stored procedure?

And then I need to insert the id's list on a temporary table

like image 317
MCSI Avatar asked Dec 20 '25 09:12

MCSI


1 Answers

You can use: Table-Valued Parameters

Table-valued parameters are a new parameter type in SQL Server 2008. Table-valued parameters are declared by using user-defined table types. You can use table-valued parameters to send multiple rows of data to a Transact-SQL statement or a routine, such as a stored procedure or function, without creating a temporary table or many parameters.

Table-valued parameters are like parameter arrays in OLE DB and ODBC, but offer more flexibility and closer integration with Transact-SQL. Table-valued parameters also have the benefit of being able to participate in set-based operations.

Eg.:

SQL Server:

Create Table-Valued Parameters:

  CREATE TYPE IDsTableType AS TABLE
  (                     
        [Product] [varchar](10) NOT NULL
  )

Pass it to Stored Procedure:

 CREATE PROCEDURE GetIDs
 (
       @TableVariable IDsTableType READONLY
 )
 AS
 BEGIN
  //Do Something

 END
 GO

C# Code for passing table valued parameter to Stored Procedure:

DataTable dataTable = GetData();
// Configure the SqlCommand and SqlParameter.
SqlCommand cmd= new SqlCommand(
    "GetIDs", connection);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter tvpParam = cmd.Parameters.AddWithValue(
    "@TableVariable", dataTable);
tvpParam.SqlDbType = SqlDbType.Structured;

Refer: Passing table-valued parameter data to a stored procedure

like image 139
Kapil Khandelwal Avatar answered Dec 22 '25 23:12

Kapil Khandelwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!