2013-04-27 131 views
0

我試圖從客戶表中檢索「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字段爲空。

需要幫助。

+0

顯示完整的代碼很難理解什麼ü在做什麼FROM HERE – 2013-04-27 04:00:35

+0

如果客戶ID爲空,你怎麼看你應該這樣做? – 2013-04-27 04:03:03

+0

如何將值從'c_id'轉移到'customer_id'? – 2013-04-27 04:06:11

回答

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(); 
    } 
相關問題