批量查询异常

时间:2018-09-18 16:06:40

标签: c# sql sql-server

当我在C#中执行以下代码时,我可以插入一条记录而不会出现问题。当我的集合中有两个对象时,出现以下错误:

  

变量名称'@scoreboardId'已被声明。变量名称在查询批处理或存储过程中必须是唯一的

是否有解决此批处理异常的方法?

public void insertActiveMonitorsForScoreboard(SqlConnection dbConn, SqlTransaction dbTrans, int scoreboardId,
                                              ObservableCollection<AvailableMonitorBo> availableMonitorsForAddOC) 
{         
    using (SqlCommand dbCommand = new SqlCommand(CreateAndDisplaySQLStrings.INSERT_SCOREBOARD_MONITORS, dbConn)) 
    {
        dbCommand.Transaction = dbTrans;

        foreach (AvailableMonitorBo bo in availableMonitorsForAddOC) 
        {
            if (bo.IsActive) 
            {
                dbCommand.Parameters.Add("scoreboardId", SqlDbType.Int).Value = scoreboardId;
                dbCommand.Parameters.Add("availableMonitorId", SqlDbType.Int).Value = bo.AvailableMonitorId;

                dbCommand.ExecuteNonQuery();
            }                   
        }               
    }
}

2 个答案:

答案 0 :(得分:5)

尝试仅添加一次参数,然后仅更改其值。

public void insertActiveMonitorsForScoreboard(SqlConnection dbConn, SqlTransaction dbTrans, int scoreboardId,
 ObservableCollection<AvailableMonitorBo> availableMonitorsForAddOC) {         
     using (SqlCommand dbCommand = new SqlCommand(CreateAndDisplaySQLStrings.INSERT_SCOREBOARD_MONITORS, dbConn)) {
           dbCommand.Transaction = dbTrans;
           dbCommand.Parameters.Add("scoreboardId", SqlDbType.Int);
           dbCommand.Parameters.Add("availableMonitorId", SqlDbType.Int);
           foreach (AvailableMonitorBo bo in availableMonitorsForAddOC) {
               if (bo.IsActive) {
                   dbCommand.Parameters["scoreboardId"].Value = scoreboardId;
                   dbCommand.Parameters["availableMonitorId"].Value = bo.AvailableMonitorId;
                   dbCommand.ExecuteNonQuery();
              }                   
        }               
    }
}

答案 1 :(得分:1)

另一种方法是将SqlCommand放入循环中。这样做的好处是,每个循环的SqlCommand都是全新的,因此在两次迭代之间不会保留任何内容。在此示例中这无关紧要,但是在其他情况下可能会如此。

public void insertActiveMonitorsForScoreboard(SqlConnection dbConn, SqlTransaction dbTrans, int scoreboardId,
 ObservableCollection<AvailableMonitorBo> availableMonitorsForAddOC) {         
   foreach (AvailableMonitorBo bo in availableMonitorsForAddOC) {
       if (bo.IsActive) {
           using (SqlCommand dbCommand = new SqlCommand(CreateAndDisplaySQLStrings.INSERT_SCOREBOARD_MONITORS, dbConn)) {
               dbCommand.Transaction = dbTrans;
               dbCommand.Parameters.Add("scoreboardId", SqlDbType.Int).Value = scoreboardId;
               dbCommand.Parameters.Add("availableMonitorId", SqlDbType.Int).Value = bo.AvailableMonitorId;
               dbCommand.ExecuteNonQuery();
          }                   
       }               
    }
}