如何执行参数化SQL查询(使用LIKE和@变量)

时间:2021-06-21 19:41:05

I want to do select query with input from user, what is the correct syntax of LIKE to use, where I should set % in the first line or second?

我想做select query with input from user, LIKE的正确语法是什么,应该在第一行或第二行设置% ?

var areaName = "SELECT AOIId FROM dbo.AreaOFInterest WHERE AOIName LIKE @AOIName ";
db.Database.ExecuteSqlCommand(areaName, @searching);

1 个解决方案

#1


1  

If you want to search for all names starting with the specified characters, specify LIKE @AOIName + '%'. For all name containing the string, specify LIKE '%' @AOIName + '%'.

如果要搜索以指定字符开头的所有名称,请指定@AOIName + '%'。对于包含字符串的所有名称,请指定“%”@AOIName +“%”。

You may also want to escape LIKE wildcards within the provided search string so that these are treated as literals:

您可能还希望在提供的搜索字符串中像通配符一样脱逃,以便将它们作为文字处理:

var aoiNameParameterValue = AOIName.Replace("[", "[[]").Replace("%", "[%]").Replace("_", "[_]").Replace("^", "[^]");

#1


1  

If you want to search for all names starting with the specified characters, specify LIKE @AOIName + '%'. For all name containing the string, specify LIKE '%' @AOIName + '%'.

如果要搜索以指定字符开头的所有名称,请指定@AOIName + '%'。对于包含字符串的所有名称,请指定“%”@AOIName +“%”。

You may also want to escape LIKE wildcards within the provided search string so that these are treated as literals:

您可能还希望在提供的搜索字符串中像通配符一样脱逃,以便将它们作为文字处理:

var aoiNameParameterValue = AOIName.Replace("[", "[[]").Replace("%", "[%]").Replace("_", "[_]").Replace("^", "[^]");