[英]Inserting multiple rows in a single SQL query from C# code?
I have multiple set of data to insert at once, say 10 rows. 我有一次要插入的多组数据,例如10行。
My table has three columns: PlanId
, MomEntryId
and CreatedBy
我的表有三列:
PlanId
, MomEntryId
和CreatedBy
Can I insert all 10 rows in a single SQL statement? 我可以在一条SQL语句中插入所有10行吗?
This is my Store procedure. 这是我的存储过程。 How can I pass 10 rows values in SP.
如何在SP中传递10行值。 I need to validate that
PlanId
and MomEntryId
too that it's value is greater than zero
or not. 我还需要验证
PlanId
和MomEntryId
的值是否greater than zero
。
CREATE PROCEDURE SP_Document_Plan_Or_MomEntry_Insert
@PlanId int = null,
@MomEntryId int = null,
@CreatedBy varchar(20)
AS
BEGIN
if(@PlanId > 0)
begin
Insert into t_Document(PlanId,CreatedBy,CreatedDate)
values
(@PlanId,@CreatedBy,GETDATE())
end
else if (@MomEntryId>0)
begin
Insert into t_Document([MomEntryId],CreatedBy,CreatedDate)
values
(@MomEntryId,@CreatedBy,GETDATE())
end
END
GO
Below is my C# code for passing parameters. 下面是我的C#代码,用于传递参数。
cblCheckList.Items.Cast<ListItem>().ToList().ForEach(d =>
{
if(d.Selected)
{
momEntry.AddDocumentDetailForMomEntry(Convert.ToInt32(d.Value), Session["userId"].ToString());
}
});
and this is for Datalayer code.I use Enterprise library
file for creating DbHelper class. 这是用于Datalayer代码的。我使用
Enterprise library
文件创建DbHelper类。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
/// <summary>
/// Summary description for MOMGateway
/// </summary>
public class MOMGateway
{
private MOMGateway()
{
//
// TODO: Add constructor logic here
//
}
///
/// This method perform insert operation in Document table
///
public static int AddDocumentEntryforMomEntry(int momEntryId,string createdBy)
{
int i = Convert.ToInt32(DBHelper.GetDatabase().ExecuteScalar("SP_Document_Plan_Or_MomEntry_Insert",
null,momEntryId,createdBy));
return i;
}
}
This is my Store procedure.
这是我的存储过程。 How can I pass 10 rows values in SP
如何在SP中传递10行值
Use User Defined Table Type for this purpose. 为此,请使用用户定义的表类型 。 You can pass the
DataTable
or your collection of object from C# code as parameter to your defined table type. 您可以将C#代码中的
DataTable
或对象集合作为参数传递给您定义的表类型。
See: Using Table-Valued Parameters in SQL Server 2008 and C# 请参阅: 在SQL Server 2008和C#中使用表值参数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.