invoke stored procedure passing a list in csharp

To invoke a stored procedure in c# while passing a list as a parameter, you can follow the below code snippet. Here we are making use of SqlClient and adding the list as a SqlParameter of SqlDbType.Structured type.

main.cs
using (SqlConnection con = new SqlConnection(connectionString))
{
    using (SqlCommand cmd = new SqlCommand("stored_procedure_name", con))
    {
        cmd.CommandType = CommandType.StoredProcedure;

        // Create a DataTable and add the list to it.
        // Here List<int> is used as an example.
        DataTable tvp = new DataTable();
        tvp.Columns.Add(new DataColumn("ID", typeof(int)));
        foreach (int item in myList)
        {
            tvp.Rows.Add(item);
        }

        // Add the DataTable as a SqlParamter of SqlDbType.Structured type
        SqlParameter parameter = new SqlParameter
        {
            ParameterName = "@ListParameter",
            SqlDbType = SqlDbType.Structured,
            TypeName = "dbo.CustomListType",
            Value = tvp
        };
        cmd.Parameters.Add(parameter);

        con.Open();
        var result = cmd.ExecuteNonQuery();
        con.Close();
    }
}
936 chars
31 lines

In the above example, "dbo.CustomListType" is a user-defined table type created in the database to match the structure of the DataTable tvp. This is necessary because SqlDbType.Structured parameter requires the name of the user-defined table type. Also, make sure to match the parameter name and type as per the stored procedure.

gistlibby LogSnag