SQL Server存储过程插入查询

时间:2022-11-16 03:54:44

In my C# code I am using :

在我使用的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");
}

The procedure 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)

I don't understand why the records get inserted 2 times in a row. For example I insert a row from the Datagridview and I get the same row twice in my SQL Server table.

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

Please note that I checked the AccessoireToSell list counts during the execution as well it say for "Count = 2" in my table I find 4 records.

请注意,我在执行期间检查了AccessoireToSell列表计数,并且在我的表中我说“Count = 2”我找到了4条记录。

Execute method :

执行方法:

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 个解决方案

#1


4  

Use this code:-

使用此代码: -

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

The difference is just add curly braces {....} to the else clause. The code without curly braces {} is executing the Cmd.ExecuteNonQuery() call twice.

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

#1


4  

Use this code:-

使用此代码: -

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

The difference is just add curly braces {....} to the else clause. The code without curly braces {} is executing the Cmd.ExecuteNonQuery() call twice.

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