0

我知道,这似乎是一百万次被问到的问题,但我再次问,因为早期的答案并不能解决我的问题。

我有这个存储过程:

ALTER PROCEDURE [dbo].[My_Save_Command_SP] 
    @Param1 varchar (50),
    @Param2 varchar (500),
    @Param3 varchar(500),
    @Param4 varchar (500),
    @Param5 varchar (500),
    @Param6 varchar (500) 
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE  @ParamID BIGINT 
    SET @ParamID = 0

    SET @ParamID = (SELECT ISNULL(ParamID,0) AS ParamID FROM t_MyTable WHERE Param1 = @Param1)

    IF @ParamID > 0 
    BEGIN
       UPDATE t_MyTable 
       SET Param2 = @Param2, Param3 = @Param3, Param4 = @Param4, 
           Param5 = @Param5, Param6 = @Param6
       WHERE Param1 = @Param1 
    END
    ELSE
    BEGIN
      SET @ParamID = (select ISNULL(MAX(ParamID),0) AS ParamID from t_MyTable) 
      SET @ParamID = @ParamID + 1

      INSERT INTO t_MyTable (ParamID, Param1, Param2, Param3, Param4, Param5, Param6) 
      VALUES (@ParamID, @Param1, @Param2, @Param3, @Param4, @Param5, @Param6)
    END
END  

下面是后端代码-

Boolean bResult = false;
Int32 nCounter = 0;
Int32 nAffectedRow = -1;

using (SqlConnection connection = DBAccessDA.CreateConnection())
{
    SqlCommand command = DBAccessDA.CreateCommand(connection);

    SqlTransaction transaction = connection.BeginTransaction();
    DBAccessDA.CreateStoredprocedure(command, "My_Save_Command_SP");

    for (int i = 0; i < pList.Count; i++)
    {
        nAffectedRow = -1;
        command.Parameters.Clear();
        DBAccessDA.AddInParameter(command, "@Param1", SqlDbType.VarChar, pList[i].Param1);
        DBAccessDA.AddInParameter(command, "@Param2", SqlDbType.VarChar, pList[i].Param2);
        DBAccessDA.AddInParameter(command, "@Param3", SqlDbType.VarChar, pList[i].Param3);
        DBAccessDA.AddInParameter(command, "@Param4", SqlDbType.VarChar, pList[i].Param4);
        DBAccessDA.AddInParameter(command, "@Param5", SqlDbType.VarChar, pList[i].Param5);
        DBAccessDA.AddInParameter(command, "@Param6", SqlDbType.VarChar, pList[i].Param6);

        // This line returns -1  
        nAffectedRow = DBAccessDA.ExecuteNonQuery(command, transaction); 

        if (nAffectedRow > 0)
        {
           nCounter++;
        }
     }

     if (nCounter == pList.Count)
     {
        transaction.Commit();
        bResult = true;
     }
     else
     {
        transaction.Rollback();
        bResult = false;
     }
  }

如果我使用相同的参数从 SQL 查询窗口运行存储过程,它会插入数据,但不是来自代码。请帮忙。谢谢。

4

1 回答 1

1

来自@dan 的评论:

我认为是SET NOCOUNT ON您的 SP 中的声明是问题所在。受影响的记录数为 0,您的后端代码回滚事务。尝试从 SP 中删除该语句。

于 2013-03-16T15:11:59.337 回答