В вашем примере выше было много небольших проблем.
Изучите приведенный ниже базовый пример как лучший подход.
// Pass in your SQL Connection object so you do not have to worry about
// multiple open connections
public int jp2Test(SqlConnection conn) {
// Verify someone did not pass in a NULL object
if (conn != null) {
string sql_text = "select count(*) from PRODUCTS where item_no=@item_no";
using (SqlCommand cmd = new SqlCommand(sql_text, conn)) {
// Get in the habit of using Parameters. If you know the SqlDbType, use one of
// the Parameter overloads that provides for this.
cmd.Parameters.AddWithValue("@item_no", itemNo);
// Open the connection if it is not already
if ((cmd.Connection.State & ConnectionState.Open) != ConnectionState.Open) {
cmd.Connection.Open();
}
// initialize an item_number variable
int selectedItemNo = -1;
object value = cmd.ExecuteScalar();
// Check for both NULL and DBNull
if ((value != null) && (value != DBNull.Value)) {
selectedItemNo = Convert.ToInt32(value);
}
// Update your SQL Text based on the value you received.
if (0 < selectedItemNo) {
sql_text = "update PRODUCTS set item_stock=@item_stock where item_no=@item_no";
// this value is already included
// cmd.Parameters.AddWithValue("@item_no", itemNo);
// this is a common value that will be added after the conditional
// cmd.Parameters.AddWithValue("@item_stock", Stock);
} else {
sql_text = "insert into PRODUCTS" +
" (item_no, item_name, price, cost, item_stock, dept_id, tax_rate1, tax_rate2, bulk_price, bulk_qty)" +
" values " +
"(@item_no,@item_name,@price,@cost,@item_stock,@dept_id,@tax_rate1,@tax_rate2,@bulk_price,@bulk_qty)";
// this value is already included
// cmd.Parameters.AddWithValue("@item_no", itemNo);
cmd.Parameters.AddWithValue("@item_name", itemName);
cmd.Parameters.AddWithValue("@price", price);
cmd.Parameters.AddWithValue("@cost", cost);
// this is a common value that will be added after the conditional
// cmd.Parameters.AddWithValue("@item_stock", Stock);
cmd.Parameters.AddWithValue("@dept_id", dept);
cmd.Parameters.AddWithValue("@tax_rate1", tax1);
cmd.Parameters.AddWithValue("@tax_rate2", tax2);
cmd.Parameters.AddWithValue("@bulk_price", BulkPrize);
cmd.Parameters.AddWithValue("@bulk_qty", BulkQty);
}
cmd.CommandText = sql_text;
cmd.Parameters.AddWithValue("@item_stock", Stock);
// Return the number of SQL records that were affected.
return cmd.ExecuteNonQuery();
}
}
// return -1 on Error
return -1;
}