Mohamed Faisal Abbas Mohamed Faisal Abbas - 3 months ago 5
SQL Question

How to pass parameter in where clause?

This is what i tried. But i am not getting any error as well as no output. what i did wrong. and why this query is not working.

SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT balance FROM PersonalLoan_tb WHERE emp_id = '@term' AND paid_or_unpaid = '@Paid' ORDER BY Id DESC";
cmd.Parameters.AddWithValue("@term", term);
cmd.Parameters.AddWithValue("@Paid", paid);


But when i try with query without parameter i am getting output.

Answer

First, you don't need the single quotes in the query string:

cmd.CommandText = "SELECT balance FROM PersonalLoan_tb WHERE emp_id = @term AND paid_or_unpaid = @Paid ORDER BY Id DESC";

That said, I caution you against using AddWithValue(). This must infer the types being passed into the string -- and any time code is not explicit, there is a danger of misinterpretation. Here, for instance, is a blog post explaining why this isn't a good idea.