Passing DataTable to stored procedure as an argument

前端 未结 2 679
别那么骄傲
别那么骄傲 2021-01-17 17:24

I have a data table created in C#.

DataTable dt = new DataTable();
dt.Columns.Add(\"Name\", typeof(string));
dt.Columns.Add(\"Age\", typeof(int));

dt.Rows.A         


        
2条回答
  •  旧时难觅i
    2021-01-17 18:26

    You can change the stored procedure to accept a table valued parameter as an input. First however, you will need to create a user defined table TYPE which matches the structure of the C# DataTable:

    CREATE TYPE dbo.PersonType AS TABLE
    (
        Name NVARCHAR(50), -- match the length of SomeTable.Column1
        Age INT
    );
    

    Adjust your SPROC:

    CREATE PROCEDURE dbo.InsertPerson
        @Person dbo.PersonType READONLY
    AS
    BEGIN
      INSERT INTO SomeTable(Column1, Column2) 
         SELECT p.Name, p.Age
         FROM @Person p;
    END
    

    In C#, when you bind the datatable to the PROC parameter, you need to specify the parameter as:

    parameter.SqlDbType = SqlDbType.Structured;
    parameter.TypeName = "dbo.PersonType";
    

    See also the example here Passing a Table-Valued Parameter to a Stored Procedure

提交回复
热议问题