【问题标题】:Dynamically add like operators in where clause在where子句中动态添加like运算符
【发布时间】:2015-06-09 11:59:34
【问题描述】:

谁能帮我解决我的问题?

我有一个最大长度的字符串数组。我想将我的所有字符串数组元素与单个 SQL 查询进行比较。我该怎么做?

string[] new = searchtext;
select Qid from questions where qdescriptions like string[0],string[1],string[2]

字符串数组长度不是固定的,是动态的。

例如:我的搜索字符串是“管理员登录错误”

然后我把它分成

admin
login
error 

作为三个部分。我的预期结果应该包含数据库中的所有这三个字符串

这样

Admin post this;
password change for login;
the error database;

希望你能理解。结果应该包含我在单个搜索查询中的所有搜索字符串..

C#代码:

 public void searchdetails(string[] searchwords) { 
     SqlConnection con = new SqlConnection(); 
     con.ConnectionString = connection; con.Open(); 

     string[] soldesc = searchwords; 
     int i = 0; 

     if (soldesc.Length == 1) { 
        string query1 = "select Qid from Questions where Qdescription like '% " + soldesc[i] + " %'"; 
     }

     SqlCommand cmds = new SqlCommand(query1, con); cmds.ExecuteNonQuery();

【问题讨论】:

  • 请提供更多细节
  • 现在看..ii 更新了
  • 每个字符串需要一个 LIKE,在 LIKE 之间放置 OR。
  • sql 中的字符串数组?
  • 您使用的是哪种 dbms 产品?

标签: sql sql-server where sql-like


【解决方案1】:

试试这个

declare @searchtext nvarchar(max) = 'abc,def,pqr'

创建一个函数

 CREATE  FUNCTION [dbo].[fn_Split](@text varchar(8000), @delimiter varchar(20))
RETURNS @Strings TABLE
(   
  position int IDENTITY PRIMARY KEY,
  value varchar(8000)  
)
AS
BEGIN

DECLARE @index int
SET @index = -1

WHILE (LEN(@text) > 0)
  BEGIN 
    SET @index = CHARINDEX(@delimiter , @text) 
    IF (@index = 0) AND (LEN(@text) > 0) 
      BEGIN  
        INSERT INTO @Strings VALUES (@text)
          BREAK 
      END 
    IF (@index > 1) 
      BEGIN  
        INSERT INTO @Strings VALUES (LEFT(@text, @index - 1))  
        SET @text = RIGHT(@text, (LEN(@text) - @index)) 
      END 
    ELSE
      SET @text = RIGHT(@text, (LEN(@text) - @index))
    END
  RETURN
END

查询

select * from yourtable y inner join (select value from 
fn_split(@searchtext,',')) as split on y.qdescriptions  like '%+split.value+%'

【讨论】:

  • 这是为哪个 dbms 服务的? (请注意,该问题没有指定 dbms。)
【解决方案2】:

您可以通过动态创建 sql 查询来做到这一点:

 string[] new = searchtext;
 String query = "select Qid from questions";

在您的应用程序中编写一个循环遍历您的搜索数组的 for 循环: 伪代码传入:

For(String searchstring in new){
   if(new.indexof(searchstring) === 0){
      query += " where qdescriptions like " + searchstring;
   }
   else{
   //depending on what you want to do here use OR or AND
      query += " or qdescriptions like " + searchstring;
   }

}

result = query.execute();

注意:这是伪代码,因为您没有说明您使用的是什么编程语言等,所以我无法告诉您 for 循环的实际语法是什么样的,或者如何保护您的查询免受 sqlInjection

您的 C# 代码应如下所示:

 public void searchdetails(string[] searchwords) { 
    SqlConnection con = new SqlConnection(); con.ConnectionString = connection; 
    con.Open(); 
    string[] soldesc = searchwords;
    string query1 =  "select Qid from Questions";
    For(int i = 0; i<soldesc.Length;i++){
       if (i == 0) { 
         query1 +=  "where Qdescription like '%" + soldesc[i] + "%'";
       }
       else{
         query1 += " AND Qdescription like '%" + soldesc[i] + "%'";
       }
    }


SqlCommand cmds = new SqlCommand(query1, con); cmds.ExecuteNonQuery();

【讨论】:

  • jeremy 你到底发布了什么我试过了..但问题是我需要用空格分割我的搜索字符串然后我需要对所有分割的字符串应用类似的条件。分割的字符串可能每时间..你能在那种情况下帮助我吗?
  • 你能在你的帖子中放一个例子吗(使用编辑功能,添加示例数据并添加预期结果)
  • 基本上你需要做的是将我的动态查询中的 OR 更改为 AND 然后它应该可以工作,如果你以某种方式将你的单个字符串(如“登录密码更改”)转换为字符串数组,如{'password','change','for','login'}(可能难易,具体取决于您使用的编程语言)
  • @nanthakumar 如果你告诉我你正在用什么语言编程,我可能会更好地帮助你做得更好
  • @jeremy 在过去的两天里真的很难与这个问题作斗争。现在很高兴。谢谢你..
【解决方案3】:

在 C# 中,您可以像这样生成查询文本...

public static void Main()
{
    string final = GenerateParameters("tableName", "fieldName", new[] {"admin", "login", " error"});

    // execute query
    // final = "SELECT * FROM tableName WHERE fieldName LIKE '%admin%' OR fieldName LIKE '%login%' OR fieldName LIKE '% error%'"
}

static string GenerateParameters(string tableName, string fieldName, IEnumerable<string> searchTerms)
{            
    string sqlParameters = string.Join(" OR ", searchTerms.Select(x => "{0} LIKE '%{1}%'".FormatWith(fieldName, x)));
    return "SELECT * FROM {0} WHERE ".FormatWith(tableName) + sqlParameters;            
}

public static class StringExtensions
{
    public static string FormatWith(this string value, params object[] args)
    {
        return String.Format(value, args);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-21
    • 2020-09-27
    • 2017-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-07
    相关资源
    最近更新 更多