简体   繁体   English

C#sql like语句不起作用

[英]C# sql like statement don't work

Hello and good day to all. 大家好,大家好。 I have a little question about like statement of sql/c#, I can't figure out why my code doesn't work. 我对sql / c#之类的语句有一个小疑问,我无法弄清楚为什么我的代码不起作用。

if (Combo_List.Text == "What")
{
   listView1.Items.Clear();
   myds.Clear();
   mydaEvents.SelectCommand = myconn.CreateCommand();
   mydaEvents.SelectCommand.CommandText = "select * from Eventstbl where What like '@what%'";
   mydaEvents.SelectCommand.CommandType = CommandType.Text;
   mydaEvents.SelectCommand.Parameters.Add("@what", SqlDbType.NVarChar, 2000, "What").Value = text_Search.Text;
   mydaEvents.Fill(myds, "Eventstbl");

   foreach (DataRow item in myds.Tables["Eventstbl"].Rows)
   {
       ListViewItem items = new ListViewItem(item["EventsID"].ToString());
       items.SubItems.Add(item["What"].ToString());
       listView1.Items.Add(items);
   }
}

The @what% won't work but when I put 'a%' all items that begin in letter a shows in my listview1. @ what%不起作用,但是当我将“ a%”中所有以字母a开头的项目都显示在listview1中时。 I don't know how to fix this issue. 我不知道如何解决此问题。 help me please. 请帮帮我。 Thank you in advance. 先感谢您。

Try this: 尝试这个:

mydaEvents.SelectCommand.CommandText = "select * from Eventstbl where What like @what + '%'";

Text inside quotes will be treated as...text - you want your parameter to be interpreted as its string value , so you have to move it out. 引号内的文本将被视为...文本-您希望将参数解释为其字符串 ,因此必须将其移出。

I'm guessing the problem is that '@what%' is being treated as a literal rather than getting replaced with the value of your parameter. 我猜测问题是'@what%'被视为文字,而不是被您的参数值替换。

Try doing @what + '%' instead. 尝试@what + '%'

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

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