[英]Inserting multiple rows in a single SQL query from C# code?
我有一次要插入的多组数据,例如10行。
我的表有三列: PlanId
, MomEntryId
和CreatedBy
我可以在一条SQL语句中插入所有10行吗?
这是我的存储过程。 如何在SP中传递10行值。 我还需要验证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
下面是我的C#代码,用于传递参数。
cblCheckList.Items.Cast<ListItem>().ToList().ForEach(d =>
{
if(d.Selected)
{
momEntry.AddDocumentDetailForMomEntry(Convert.ToInt32(d.Value), Session["userId"].ToString());
}
});
这是用于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;
}
}
这是我的存储过程。 如何在SP中传递10行值
为此,请使用用户定义的表类型 。 您可以将C#代码中的DataTable
或对象集合作为参数传递给您定义的表类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.