简体   繁体   中英

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. 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.

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.
A few days ago, I implemented the WildCard search to do the same thing.
I retrieve the record from a table using entity framework and use LINQ to match record.
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. You can add multiple columns with Logical OR operation || 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.

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.

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.

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