【问题标题】:The variable name @IdLiquidacion has already been declared. Variable names must be unique within a query batch or stored procedure.'变量名称@IdLiquidacion 已被声明。变量名称在查询批处理或存储过程中必须是唯一的。
【发布时间】:2018-04-27 16:06:52
【问题描述】:

在数据库中插入信息时遇到以下问题

public void Insertar()
{
   SqlConnection con = new SqlConnection();
   con.ConnectionString = "Data Source=BD-DLLO-SP2016;Initial Catalog=GobernacionCesar;Integrated Security=True";

   con.Open();

   string query = "INSERT INTO Liquidacion (IdLiquidacion, IdPeriodo, FechaGeneracion, Usuario) VALUES(@IdLiquidacion, @IdPeriodo, @FechaGeneracion, @Usuario)";

   SqlCommand com1 = new SqlCommand(query, con);

   foreach (GridViewRow gridRow in GridView4.Rows)
   {
       Iniciar();
       com1.Parameters.AddWithValue("@IdLiquidacion", A);
       com1.Parameters.AddWithValue("@IdPeriodo", cell);
       com1.Parameters.AddWithValue("@FechaGeneracion", DateTime.Now.ToString());
       com1.Parameters.AddWithValue("@Usuario", gridRow.Cells[0].Text);

       com1.ExecuteNonQuery();
   }

   con.Close();
   return;
}

【问题讨论】:

    标签: asp.net


    【解决方案1】:

    移动命令

    SqlCommand com1 = new SqlCommand(query, con);
    

    到循环的开头:

    foreach (GridViewRow gridRow in GridView4.Rows)
    {
        SqlCommand com1 = new SqlCommand(query, con);
        ....
    }
    

    【讨论】:

      【解决方案2】:

      你应该

      • 定义参数在循环之外
      • 设置循环内参数的值

      像这样:

      SqlCommand com1 = new SqlCommand(query, con);
      
      // define parameters - you need to adapt the datatypes - I was only guessing
      com1.Parameters.Add("@IdLiquidacion", SqlDbType.Int);
      com1.Parameters.Add("@IdPeriodo", SqlDbType.VarChar, 50);
      com1.Parameters.Add("@FechaGeneracion", SqlDbType.DateTime);
      com1.Parameters.Add("@Usuario", SqlDbType.VarChar, 100);
      
      foreach (GridViewRow gridRow in GridView4.Rows)
      {
         Iniciar();
      
         // inside the loop, only SET the values
         com1.Parameters["@IdLiquidacion"].Value = A;
         com1.Parameters["@IdPeriodo"].Value = cell;
         com1.Parameters["@FechaGeneracion"].Value = DateTime.Now;
         com1.Parameters["@Usuario"].Value = gridRow.Cells[0].Text;
      
         com1.ExecuteNonQuery();
      }
      

      【讨论】:

        【解决方案3】:

        您正在循环中添加参数。如果您在添加之前清除它们,这应该可以工作。

        【讨论】:

          猜你喜欢
          • 2020-02-01
          • 2015-05-26
          • 2019-04-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-20
          • 2020-08-23
          相关资源
          最近更新 更多