简体   繁体   English

如何搜索数据库项的子字符串?

[英]How to search for a substring of a database item?

I'm working on a .NET system I'm not familiar with and I'm trying to solve a problem in which when I search for an item, it only works if I input the initial characters. 我正在使用一个我不熟悉的.NET系统,正在尝试解决一个问题,当我搜索一个项目时,该项目仅在输入初始字符时才起作用。 Ex: If I want to search for a Mountain Lion and input "Lion", it'll only list Lion and Lion fish. 例如:如果我要搜索狮子山并输入“狮子”,则只会列出狮子和狮子鱼。 If I input "M", it'll show Mountain Lion among all other animals which start with M. I want it to work regardless of where the string is located on the item, so it returns every item which contains "lion" somewhere. 如果输入“ M”,它将在所有其他以M开头的动物中显示“山狮”。我希望它能正常工作,而不管字符串在项目上的位置如何,因此它将返回每个包含“狮子”的项目。

Here's some code showing how it currently works. 这是一些代码,显示当前的工作方式。

[HttpPost]
    public ActionResult PerformSearch(FormCollection collection)
    {
        var parameters = new List<DataAccessParameter>();
        parameters.Add(new DataAccessParameter("@p_id_animal", System.Data.DbType.Int32, collection["id_animal"].ToDatabase()));
        parameters.Add(new DataAccessParameter("@p_nm_animal", System.Data.DbType.String, collection["nm_animal"].ToUpper().ToDatabase())); //animal name



        var list = DataHelper.Execute<BVAnimalSearch>(
             System.Data.CommandType.StoredProcedure, "sp_search_animal", parameters,
             dr => new BVAnimalSearch
             {
                 id_doenca_animal = dr.ToInt("id_animal"),
                 nm_doenca_animal = dr.ToString("nm_animal"),

             }).ToList();

        return new ObjectResult<object>(new { success = true, data = list, total = list.Count });
    }

[HttpPost]
    public ActionResult ReturnSearch(List<BVAnimalSearch> listSelected)
    {
        var qry = from item in listSelected
                  select new BVAnimal
                  {
                      idAnimal = item.id_animal,
                      nmAnimal = item.nm_animal,
                  };
        return new ObjectResult<ActionResponse>(new ActionResponse { success = true, data = qry });
    }

I'd like to know how to modify this code to do what I asked. 我想知道如何修改此代码以执行我的要求。 Let me know if another part of the code is needed. 让我知道是否需要代码的另一部分。

EDIT: Stored procedure: 编辑:存储过程:

/****** Object:  StoredProcedure [dbo].[sp_search_animal] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER  PROCEDURE [dbo].[sp_search_animal] 
(  
 @p_id_animal int = null,    
 @p_nm_animal varchar(200) = null,    
)     
AS     
DECLARE    
    @sql_where NVARCHAR(1000),    
    @sql_expr NVARCHAR(2000),    
 @sql_orderby NVARCHAR(500),    
 @sql_groupby NVARCHAR(500);    
BEGIN     

 SET @sql_orderby = ' ORDER BY 1 ';    
 SET @sql_where = '';    

 IF @p_id_animal IS NOT NULL    
  set @sql_where = @sql_where + ' AND d.id_animal = @p_id_animal '      

 ELSE IF @p_nm_animal IS NOT NULL    
  set @sql_where = @sql_where + ' AND d.nm_animal LIKE @p_nm_animal +''%'' '    

END  


 SET @sql_expr = @sql_expr + @sql_where + @sql_orderby;


 EXECUTE sp_executesql @sql_expr, 
  N'@p_id_animal int = NULL,    
  @p_nm_animal VARCHAR(200) = NULL',    
  @p_id_animal,     
  @p_nm_animal 
END    

Here is what I understand from your question. 这是我从您的问题中了解的内容。 You need to search for something, from your saved record in the database. 您需要从数据库中保存的记录中搜索内容。 eg You are passing Loin as input, and retrieve all records from a table's column having Loin in it. 例如,您要传递Loin作为输入,并从其中包含Loin的表的列中检索所有记录。
A few days ago, I implemented the WildCard search to do the same thing. 几天前,我实施了WildCard搜索以执行相同的操作。
I retrieve the record from a table using entity framework and use LINQ to match record. 我使用实体框架从表中检索记录,并使用LINQ匹配记录。
If any column contains some information related to search query, add it into a list. 如果任何列包含与搜索查询有关的某些信息,请将其添加到列表中。

    var animals = await (from _a in _dbContext.animals
                         where ( _a.Name.Contains(searchQuery, StringComparison.InvariantCultureIgnoreCase))
                         select new Animal
                         {
                           /* properties of animal that you want to select */
                         }).ToListAsync();

Where name is the column of the table. 其中name是表的列。 You can add multiple columns with Logical OR operation || 您可以使用逻辑OR操作||添加多个列。 to check on multiple columns of the table in which you want to search. 检查要在其中搜索表的多个列。

You can also do this in your stored procedure with the LIKE operator. 您也可以使用LIKE运算符在存储过程中执行此操作。

Already solved it btw. 顺便说一句,已经解决了。 When comments mentioned the stored procedure, I realized where the problem was. 当评论提到存储过程时,我意识到问题出在哪里。 Just changed this line adding the % before the string as well. 只需更改此行,并在字符串之前添加%。

set @sql_where = @sql_where + ' AND d.nm_animal LIKE ''%''+ @p_nm_animal +''%'' '

Thanks. 谢谢。

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

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