【问题标题】:SQL C# Generating SQL statement with LIKE and wildcards; giving Incorrect syntax near 'bla'SQL C# 使用 LIKE 和通配符生成 SQL 语句;在“bla”附近给出不正确的语法
【发布时间】:2012-11-14 13:08:50
【问题描述】:

所以我有一个名为 arr 的 ArrayList,其中包含诸如“decoration”、“metal”、“paper”等字符串。

我想要做的是循环遍历该 ArrayList,将每个标签添加到一个查询字符串中,使用该查询字符串从数据库中获取数据。 目前我有这样的事情:

String strSel="select * from Table1 where Tags";

for(int x=0;x<arr.Count;x++){
  if (x == arr.Count - 1)
    {
      strSel += " like '%'"+arr[x]+"'%'";
    }
      else
    {
      strSel += " like '%'" + arr[x] + "'%' or Tags";
    }
}

cmdSel=new SqlCommand(strSel,connectionName);
sqlDataReaderName=cmdSel.ExecuteReader();

无论如何,我收到有关“bla 附近的语法不正确”的错误...它可能与单引号或通配符有关,但我无法弄清楚。我做错了什么?

【问题讨论】:

    标签: c# sql syntax quotes


    【解决方案1】:

    你应该删除额外的单引号之前之后percent symbol

    strSel += " like '%" + arr[x] + "%'";
    

    抛出错误的原因是因为您的查询是这样形成的

    select * from Table1 where Tags like '%'hello'%'
                                           ^     ^ extra single quote that
                                                   should be removed
    

    【讨论】:

      【解决方案2】:

      是的 Kuya John 是正确的,额外的 ' 导致了问题

              String strSel = "select * from Table1 where Tags";
              string[] arr = new string[] { "This", "That", "Something" };
              for (int x = 0; x < arr.Count(); x++)
              {
                  if (x == arr.Count() - 1)
                  {
                      strSel += string.Format(" like '%{0}%' ", arr[x]);
                  }
                  else
                  {
                      strSel += string.Format(" like '%{0}%' or Tags", arr[x]);
                  }
              }
      

      没有额外的',这表现得很好

      【讨论】:

        猜你喜欢
        • 2018-06-26
        • 1970-01-01
        • 1970-01-01
        • 2017-02-07
        • 2011-10-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多