我很難運行此代碼,我有兩個選擇語句在一個單一的查詢與不同的「聲明」,我想要的只是將其插入數據庫只是「ID」只有這裏是代碼,如何從單個查詢中的兩個不同的select語句獲取ID?
sqc.Open();
cmd = sqc.CreateCommand();
cmd.CommandText = "Select DepID from UserDept where Department [email protected] and Position [email protected] union all Select SalaryID from Salaries where Gradenumber [email protected] and StepNumber [email protected]";
cmd.Parameters.AddWithValue("@depe", cmbDept.SelectedItem.ToString());
cmd.Parameters.AddWithValue("@posi", cmbPos.SelectedItem.ToString());
cmd.Parameters.AddWithValue("@gn", cmbgrade.SelectedItem.ToString());
cmd.Parameters.AddWithValue("@sn", cmbstep.SelectedItem.ToString());
sda = new SqlDataAdapter(cmd);
dt = new DataTable();
sda.Fill(dt);
foreach (DataRow rr in dt.Rows)
{
cmd = sqc.CreateCommand();
cmd.CommandText = "insert into UserInfo2 (AccountID,DeptID,SalaryGrade,DateEmp,DateHired) Values (@idd,@dep,@sal,@emp,@hired)";
cmd.Parameters.AddWithValue("@idd", "crap");
cmd.Parameters.AddWithValue("@dep", rr[0].ToString());
cmd.Parameters.AddWithValue("@sal", rr[1].ToString());
cmd.Parameters.AddWithValue("@emp", dtpEmployed.Value.ToShortDateString());
cmd.Parameters.AddWithValue("@hired", dtpPromoted.Value.ToShortDateString());
cmd.ExecuteNonQuery();
MessageBox.Show("Information successfully saved!", "Information!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
sqc.Close();
什麼即時試圖做的是,如果列名DEPID子項目必須dep232和SALARYID是SAL 232
我嘗試在INSERT語句
cmd.Parameters.AddWithValue("@dep", rr[0].ToString());
cmd.Parameters.AddWithValue("@sal", rr[0].ToString());
這段代碼的輸出是列名DEPID它有子項sal243,它應該只有SALARYID 並且還有另一個DEPID是dep243的數據,但salaryID也有dep243。
你到底想做什麼?兩張桌子之間沒有聯繫。這樣你最終會搞亂第三張表中的所有數據。 – Shahbaz