how to execute SQL with if condition in c#?
This is my query and went i execute this query i get an error saying “Invalid SQL statement; expected ‘DELETE’, ‘INSERT’, ‘PROCEDURE’, ‘SELECT’, or ‘UPDATE’.”
I m using MS ACCESS as back end
mycon.ConnectionString = ConnString;
mycon.Open();
string mySelectQuery = "IF (EXISTS (SELECT * FROM Employee AS t1 WHERE t1.ssn ='"+textBox4.Text+"' "+
"))begin UPDATE Employee SET "+
"fname ='"+textBox1.Text+"' ,"+
"minit ='"+textBox2.Text+"' ," +
"lname ='" + textBox3.Text+"', " +
"ssn ='" +textBox4.Text+"', " +
"bdate ='" +textBox5.Text+"', " +
"address ='" +textBox6.Text+"', " +
"sex ='" +textBox7.Text+ "', " +
"salary ='" +textBox8.Text+"', " +
"superssn ='" +textBox9.Text+"', " +
"dno ='" +comboBox2.Text+"'" +
" WHERE ssn = '"+textBox4.Text+"' "+
"end "+
"else "+
" begin "+
" INSERT INTO employee values ('"+textBox1.Text+"','"+textBox2.Text+"','"+textBox3.Text+"','"+textBox4.Text+"','"+textBox5.Text+"','"+textBox6.Text+"','"+textBox7.Text+"','"+textBox8.Text+"','"+textBox9.Text+"','"+comboBox2.Text+"')"+
" end";
OleDbCommand myCommand = new OleDbCommand(mySelectQuery, mycon);
int Success= myCommand.ExecuteNonQuery();
MS Access doesn’t support the
IFstatement. Norelseorbegin. You’ll have to do this in your C# code, such as performing your"SELECT * FROM Employee AS t1 WHERE t1.ssn ='"+textBox4.Text + "'";query first and then performing the next one if there are results.Also, you should either use a parameterized queries or escape the values of you text boxes.