即使命令在SQL Server 2008中成功执行,数据也未保存到数据库中?

时间:2013-01-23 05:13:25

标签: c#-4.0 sql-server-2008-r2

我知道,这似乎是一个百万时间问题,但我再次问,因为,早期的答案并没有解决我的问题。

我有这个存储过程:

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查询窗口运行存储过程,它会插入数据,但不能从代码中插入。请帮忙。感谢。

1 个答案:

答案 0 :(得分:1)

来自@ dan的评论:

  

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