简体   繁体   English

如何在where子句中传递参数?

[英]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. 但是,当我尝试不带参数的查询时,我正在输出。

Don't use single Quotes ' in parameters of Query 不要在查询参数中使用single Quotes '

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);

As per my comment - single quotes should not be there - they change the parameter to a literal. 根据我的评论-单引号不应出现-它们将参数更改为文字。 So your query is looking for a balance where the emp_id is the string '@term' and is won't be using the parameter passed in. Try 因此,您的查询正在寻找emp_id为字符串'@term'并且不会使用传入参数的平衡。

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);

Anything specified between single quote ('), will be considered as a string. 在单引号(')之间指定的任何内容都将被视为字符串。 So write parameter name without quote (') and it will work. 因此,编写参数名称时不带引号('),它将起作用。

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

rest of the code will be same. 其余代码将相同。

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);

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() . 就是说,我告诫您不要使用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. 例如, 这里是一篇博客文章,解释了为什么这不是一个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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