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. I have also tried using @text instead of "?" but it doesn't work. Any suggestions?
By the way it gives Incorrect syntax near '?' SqlException
Replace the ?
with some SQL variable and change your command.Parameters.Add
like below
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));
it gives Incorrect syntax near '@text' exception.
But..
I used ".... LIKE @text" and passing the parameter with command.Parameters.Add(new SqlParameter("@text", "%"+text+"%"));
it works.
您可以只使用字符串串联。
cmd = cmd.Replace("?","'%" + text + "%'");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.