Passing datatable to a stored procedure

后端 未结 3 611
长发绾君心
长发绾君心 2020-12-01 09:55

I have a datatable created in C#.

using (DataTable dt = new DataTable())
{
    dt.Columns.Add(\"MetricId\", typeof(int));
    dt.Columns.Add(\"Descr\", typeo         


        
相关标签:
3条回答
  • 2020-12-01 10:15
    1. You need to define a Table Type that you want to pass in User-Defined Table Types in your database.

    2. Then you need to add the parameter in your Stored Procedure to pass it in like this:

      @YourCustomTable AS [dbo].YourCustomTable Readonly,
      
    3. Then, when you have your rows setup, call it like this:

      // Setup SP and Parameters
      command.CommandText = "YOUR STORED PROC NAME";
      command.Parameters.Clear();
      command.CommandType = CommandType.StoredProcedure;
      command.Parameters.AddWithValue("@someIdForParameter", someId);
      command.Parameters.AddWithValue("@YourCustomTable",dtCustomerFields).SqlDbType = SqlDbType.Structured;
      
      //Execute
      command.ExecuteNonQuery();
      

    This should resolve your problem

    0 讨论(0)
  • 2020-12-01 10:16

    We generally squirt the data into XML documents and pass the data to the database as an NTEXT parameter.

    0 讨论(0)
  • 2020-12-01 10:32

    You can use a Table Valued Parameter as of SQL Server 2008 / .NET 3.5....

    Check out the guide on MSDN

    Also, as there other options available, I have a comparisonof 3 approaches of passing multiple values (single field) to a sproc (TVP vs XML vs CSV)

    0 讨论(0)
提交回复
热议问题