[英]sql parametrized query using LIKE
I have tried to pass a parameter to quert but it doesn't work. 我试图将参数传递给队列,但它不起作用。 What is the best way to do it? 最好的方法是什么? I do not want to concatenate strings. 我不想连接字符串。 Here is my query: 这是我的查询:
string cmd = @"
SELECT
*
FROM
TABLE
WHERE
p.PromptTypeID = pt.ID
AND p.PromptDomainID = pd.ID
AND p.LanguageID = pl.ID
AND p.VoiceID = pv.ID
AND p.Active='Y'
AND PromptText LIKE ?
ORDER BY
p.ID DESC";
using (SqlCommand command = new SqlCommand())
{
command.CommandText = cmd;
command.Transaction = transac;
command.Connection = cnn;
command.Parameters.Add("?", SqlDbType.VarChar, 50).Value = "%" + text + "%";
using (SqlDataAdapter adp = new SqlDataAdapter(command))
{
adp.Fill(dt);
}
}
I couldn't pass the value with LIKE operator. 我无法通过LIKE运算符传递值。 I have also tried using @text instead of "?" 我也尝试使用@text而不是“?” but it doesn't work. 但这不起作用。 Any suggestions? 有什么建议么?
By the way it gives Incorrect syntax near '?' 顺便说一句,它在'?'附近给出不正确的语法 SqlException SqlException异常
Replace the ?
更换?
with some SQL variable and change your command.Parameters.Add
like below 使用一些SQL变量并更改您的command.Parameters.Add
如下
PromptText LIKE %@Text%
cmd.Parameters.Add("@Text", varYourtext);
Try 尝试
AND PromptText LIKE @text
and 和
command.Parameters.Add("@text"...
I have finally found the solution. 我终于找到了解决方案。 When I use ".... LIKE %@text%" and passing the parameter with command.Parameters.Add(new SqlParameter("@text", text));
当我使用“ .... LIKE%@ text%”并通过command.Parameters.Add(new SqlParameter("@text", text));
传递参数时command.Parameters.Add(new SqlParameter("@text", text));
it gives Incorrect syntax near '@text' exception. 它在'@text'异常附近给出了错误的语法。
But.. 但..
I used ".... LIKE @text" and passing the parameter with command.Parameters.Add(new SqlParameter("@text", "%"+text+"%"));
我使用了“ .... LIKE @text”并通过command.Parameters.Add(new SqlParameter("@text", "%"+text+"%"));
传递参数command.Parameters.Add(new SqlParameter("@text", "%"+text+"%"));
it works. 有用。
您可以只使用字符串串联。
cmd = cmd.Replace("?","'%" + text + "%'");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.