Setting value of parameter containing “ ' ” (apostrophe) used in LIKE query

前端 未结 3 996
盖世英雄少女心
盖世英雄少女心 2021-01-22 02:04

I have the following query in ASP.NET/C# code which is failing to return any values using a parameter...

select * from MyTable where MyTable.name LIKE @search


        
相关标签:
3条回答
  • 2021-01-22 02:52

    I think the issue is that you're escaping the quotes in your search parameter, when the SQL parameter does that for you.

    The percent signs should be inside the SQL Parameter value; your query just references the parameter plainly. The SQL should look like this:

    select * from MyTable where MyTable.name LIKE @search
    

    And the code should look like this:

    string search = "MyValue'ToSearchForWith'Quotes";
    myCmd.Parameters.AddWithValue("@search", "%" + search + "%");
    

    Note that search is the original value, not escaped.

    0 讨论(0)
  • 2021-01-22 03:01

    within t-sql you escape ' by using two: ''

    @query=' this doesn''t cause a problem'

    0 讨论(0)
  • 2021-01-22 03:07

    On the SQL side, this is correct:

    select * from MyTable where MyTable.name LIKE '%' + @search + '%'
    

    If the parameter was passed in from outside, it would not matter if it contained single quotes.

    On the API side, this should be correct:

    myCmd.Parameters.AddWithValue("@search", "%" + search + "%");
    

    The AddWithValue() method does all the necessary escaping for you, no need to interfere.

    0 讨论(0)
提交回复
热议问题