如何将datatable参数传递给存储过程sql server?

时间:2014-03-23 13:55:17

标签: sql-server stored-procedures datatable

我需要将数据表传递给以下存储过程

 create procedure insert_data
(@a int ,
@b DataTable)
as 
Begin 
......
end

我使用C#

1 个答案:

答案 0 :(得分:4)

你需要做一些事情才能实现这一目标,因为你想传递一个表作为参数,你需要创建一个(1)表类型和(2)让你的商店过程接受一个参数类型。

以下是创建TABLE TYPE所需的步骤。

表类型

CREATE TYPE dbo.DataTable AS TABLE 
 (
    -- define table structure here
  )
 GO

<强>程序

现在让你的过程接受该表类型的参数。

create procedure insert_data
@a int ,
@b dbo.DataTable READONLY    --<-- Note this is read only param
as 
Begin 
......
end

这个传递的参数将是只读参数,所以如果你需要操作这个参数中传递的值,你需要在程序内的表变量或临时表中获取这些值,然后才能进行任何更新或插入对他们的操作。

消费C#

您可以使用DataTable类来创建与sql server中的表类型匹配的该类型的新实例。像这样......

DataTable dt = new DataTable("DataTable"); 

// Add columns to this object same as the type in sql server

dt.Columns.Add("Column1", typeof(string)); 
dt.Columns.Add("Column2", typeof(Int32)); 

//Populate the dt object 

dt.Rows.Add("Value1", 1); 
dt.Rows.Add("Value2", 2); 
dt.Rows.Add("Value2", 3); 
相关问题