Reputation: 6762
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
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
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