简体   繁体   中英

what is the proper query for insert and select statement with Like clause?

i have this query and it gives me error which is unavaible to insert null on table tbl_emp_gs. i don't know what is wrong with my code here.

con.Open();
sqc = con.CreateCommand();
string query1 = "INSERT INTO tbl_emp_gs (EmployeeID,StepID) VALUES ('"+ lblEmpID.Text +"', (Select StepID from tbl_gradestep where StepID Like @grade))";
 sqc.Parameters.AddWithValue("@grade",cmbStepNumber.Text);
 sqc.CommandText = query1;
 sdr = sqc.ExecuteReader();
 MessageBox.Show("Data Saved.", "Message",MessageBoxButtons.OK,MessageBoxIcon.Information);

i want to get the step ID from tbl_gradestep table,

The Inner query is returning NULL . You should follow like syntax in order to retrieve a correct result (If it exists) :

string query1 = "INSERT INTO tbl_emp_gs (EmployeeID,StepID) VALUES ('"+ lblEmpID.Text +"', (Select StepID from tbl_gradestep where StepID Like @grade))";

sqc.Parameters.AddWithValue("@grade", "%" + cmbStepNumber.Text + "%");

I suggest using sqc.ExecuteNonQuery() unless you have a valid reason to execute a data reader.

Also, it is not recommended to concat strings in SQL statements.

You should use a insert Select and not a values with select .. in this way you perform the insert only if the select work and if you have mode then on rows in select you insert the same number of rows

Assuming that @grade is the search pattern

"INSERT INTO tbl_emp_gs (EmployeeID,StepID)
 SELECT ('"+ lblEmpID.Text +"', StepID 
from tbl_gradestep where StepID Like concat('%', @grade, '%'))"
string query1 = "INSERT INTO tbl_emp_gs (EmployeeID,StepID) VALUES ('"+ lblEmpID.Text +"', (Select StepID from tbl_gradestep where StepID Like '%@grade%'))";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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