如何从表中检索数据并插入另一个表?

时间:2013-04-27 03:57:58

标签: c# asp.net sql

我正在尝试从Customer表中检索“customer_id”并将其插入

fare_tariff(tariff_id, customer_id, total_price)

所以我从Customer表中检索customer_id,如下所示:

using (SqlCommand command = new SqlCommand("SELECT customer_id FROM Customer WHERE UserName = '" + username + "' Password = '"+password +"' ", connection))
{
    string cust_id = customer_id.ToString();
    SqlDataReader myReader = command.ExecuteReader();

    if (myReader.Read())
    {
        cust_id = myReader["customer_id"].ToString();
    }

    int c_id = Convert.ToInt32(cust_id);

    myReader.Close();
    custID(c_id);
}

并将customer_id插入表fare_tariff,如下所示:

using (SqlCommand command = new SqlCommand("INSERT INTO flight_reservation(tariff_id, customer_id, total_price) VALUES(@val1,@val2,@val3)", connection))
{

    command.Parameters.Add("@val1", SqlDbType.Int).Value = tariff_id;
    command.Parameters.Add("@val2", SqlDbType.Int).Value = customer_id;
    command.Parameters.Add("@val3", SqlDbType.VarChar).Value = total_price.ToString();

    command.ExecuteNonQuery();
}  

我将customer_id声明为存储customer_id的变量。

问题是:成功插入了tariff_id和total_price,但是customer_id列尚未归零。

需要帮助。

1 个答案:

答案 0 :(得分:0)

将数据提取到客户端并逐行返回服务器 很可能产生很大的开销。有更好的方法来做同样的事情, 所谓的“插入/选择”查询:

  using (SqlCommand command = connection.CreateCommand()) {
    command.CommandText =
      "insert into Flight_Reservation(\n" +
      "            Customer_Id,\n" +
      "            Tariff_Id,\n" +
      "            Total_Price)\n" +
      "     select Customer_Id,\n" +
      "            @prm_Tariff_Id,\n" +
      "            @prm_Total_Price\n" +
      "       from Customer\n" +
      "      where (UserName = @prm_UserName)\n" + 
      "            (Password = @prm_Password)"; 

    command.Parameters.Add("@prm_Tariff_Id", SqlDbType.VarChar, 80).Value = tariff_id;
    command.Parameters.Add("@prm_Total_Price", SqlDbType.VarChar, 80).Value = total_price.ToString();
    command.Parameters.Add("@prm_UserName", SqlDbType.VarChar, 80).Value = username;
    command.Parameters.Add("@prm_Password", SqlDbType.VarChar, 80).Value = password;

    command.ExecuteNonQuery();
  }