我在一个我不熟悉的 .NET 系统上工作,我试图解决一个问题,当我搜索一个项目时,它只有在我输入初始字符时才有效。例如:如果我想搜索一个山狮并输入“狮子”,它只会列出狮子和狮子鱼。如果我输入“M”,它会在所有其他以 M 开头的动物中显示 Mountain Lion。我希望它无论字符串位于项目上的哪个位置都能正常工作,因此它会返回每个包含“lion”的项目。
这里有一些代码显示了它目前是如何工作的。
[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 });
}
我想知道如何修改此代码以执行我的要求。如果需要代码的另一部分,请告诉我。
编辑:存储过程:
/****** 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
顺便说一句,已经解决了。当评论提到存储过程时,我意识到问题出在哪里。刚刚更改了这一行,也在字符串前添加了 %。
set @sql_where = @sql_where + ' AND d.nm_animal LIKE ''%''+ @p_nm_animal +''%'' '
谢谢。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句