Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

c# - Passing DataTable to stored procedure as an argument

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.Add("James", 23);
dt.Rows.Add("Smith", 40);
dt.Rows.Add("Paul", 20);

I want to pass this to the following stored procedure.

CREATE PROCEDURE  SomeName(@data DATATABLE)
AS
BEGIN
    INSERT INTO SOMETABLE(Column2,Column3)
    VALUES(......);
END

My question is : How do we insert those 3 tuples to the SQL table ? do we need to access the column values with the dot operator ? or is there any other way of doing this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...