Search code examples
c#sqlsql-serverasp.net-mvcsql-like

How to execute parameterized SQL query (using LIKE with @ variable)


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?

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

Solution

  • 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 + '%'.

    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("^", "[^]");