简体   繁体   English

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

[英]How to retrieve a data from a table and insert into another table?

I am trying to retrieve "customer_id" from Customer table and insert it into 我正在尝试从客户表中检索“ customer_id”并将其插入

fare_tariff(tariff_id, customer_id, total_price)

So I retrieve the customer_id from Customer table as below: 因此,我从“客户”表中检索“ 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);
}

and insert the customer_id into table fare_tariff like below: 并将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();
}  

I declared customer_id as a variable for storing customer_id. 我将customer_id声明为用于存储customer_id的变量。

Problem is : tariff_id and total_price inserted successfully but the column customer_id is null yet. 问题是:成功插入了riff_id和total_price,但customer_id列为空。

Help needed. 需要帮助。

Fetching data to the client and returning row by row back to the server can well produce big overhead. 将数据提取到客户端,然后将数据逐行返回服务器很可能会产生很大的开销。 There's better way to do the same, so called "insert/select" query: 有更好的方法可以执行此操作,因此称为“插入/选择”查询:

  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();
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM