SQL Server存储过程插入查询

时间:2017-01-07 20:10:07

标签: c# sql-server

在我使用的C#代码中:

public void Add(int ID)
{
    foreach (AccessoireToSell item in OrderToAdd.Accessoires)
    {
        Adder(item.Ref, item.Qte, item.SellPrice, ID);
    }
}

private void Adder(int refid,int Qtetosell,string sellprice,int ID)
{
    SqlParameter[] param = new SqlParameter[4];

    param[0] = new SqlParameter("@AccessoireID", SqlDbType.Int);
    param[0].Value = refid;

    param[1] = new SqlParameter("@Qte", SqlDbType.Int);
    param[1].Value = Qtetosell;

    param[2] = new SqlParameter("@Price", SqlDbType.VarChar, 50);
    param[2].Value = sellprice;

    param[3] = new SqlParameter("@ORDERID", SqlDbType.Int);
    param[3].Value = ID;

    Function.Execute(param, "AccessoiresAddOrder");
}

程序AccessoiresAddOrder

ALTER PROCEDURE [dbo].[AccessoiresAddOrder]
    @ORDERID int,
    @AccessoireID int,
    @Qte int,
    @Price Varchar(50)
AS
    INSERT INTO [dbo].[Accessoires_OrderDetails] ([orderID], [AccessoireID],[Qte], [Price])
    VALUES (@ORDERID, @AccessoireID, @Qte, @Price)

我不明白为什么记录会连续插入2次。例如,我从Datagridview插入一行,并在SQL Server表中两次获得相同的行。

请注意,我在执行过程中检查了AccessoireToSell列表计数,并说明了" Count = 2"在我的表中,我找到了4条记录。

执行方法:

public void Execute(SqlParameter[] param, string ProcName)
{
    SqlCommand Cmd = new SqlCommand();
    Cmd.CommandText = ProcName;
    Cmd.CommandType = CommandType.StoredProcedure;

    if (param != null)
    {
        Cmd.Parameters.AddRange(param);
    }

    Cmd.Connection = Base.Connection;

    if (Base.Status() == true)
        Cmd.ExecuteNonQuery();
    else
        Base.Open();
        Cmd.ExecuteNonQuery();
}

1 个答案:

答案 0 :(得分:4)

使用此代码: -

if (Base.Status() == true)
    Cmd.ExecuteNonQuery();
else
{
     Base.Open();
     Cmd.ExecuteNonQuery();
}

不同之处只是将大括号{....}添加到else子句中。没有大括号{}的代码正在执行Cmd.ExecuteNonQuery()次调用。