Kurkula
Kurkula

Reputation: 6762

csharp using sql query with special characters

I have a scenario in my csharp code where I am trying to get records with special characters / and % using sql query.

I tried executing query in sql query analyzer and it worked fine after adding square brackets.

Select * from tblDetails where name like '%[\]%' or name like '%[%]%' 

But it fails when I use it in csharp

string sqlQuery = "Select * from tblDetails where name like '%[/]%' or name like '%[%]%' ";
using (SqlCommand command = new SqlCommand(strQuery, strConnection))

Upvotes: 1

Views: 2291

Answers (2)

DWright
DWright

Reputation: 9500

The following code works for me:

using (SqlConnection conn = new SqlConnection())
{
    conn.ConnectionString = "Integrated Security=true;Initial Catalog=xyz;server=abc";
    string sqlQuery = "Select * from myTable where name like '%[\\]%' or name like '%[%]%'";
    conn.Open();
    using (SqlCommand command = new SqlCommand(sqlQuery, conn))
    {
        var result = command.ExecuteReader();
    }
}

Upvotes: 1

RedOctober
RedOctober

Reputation: 215

Try this

string sqlQuery = @"Select * from tblDetails where name like '%[\]%' or name like '%[%]%' ";

@-operator ignores special characters in a string

EDIT: Well now this solution will work just fine

Upvotes: 1

Related Questions