0

I am currently fetching a dataset from following query select * from TableName WHERE ColumnName ='values''s' query executes without any error and return dataset was empty rows. When i execute the same in SQL Worksheets it return data

Following code for ref.

string sqlQuery = "select * from TableName WHERE Name ='McNaught''s'";
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = sqlQuery;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
DataSet ds = new DataSet();            
conn.Open();
adapter.Fill(ds);
conn.Close();
SAA
  • 21
  • 4

3 Answers3

2

Please try this:

string sqlQuery = 'SELECT * FROM TableName WHERE Name ="McNaught\'s"'
Ilyes
  • 14,640
  • 4
  • 29
  • 55
Kashish Agarwal
  • 303
  • 1
  • 15
0

The Problem is you need to provide Escape Sequence before the second ' so that compiler can distinguish between the previous apostrophe. Try this.

string sqlQuery = "select * from TableName WHERE Name ='McNaught'\'s'";
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = sqlQuery;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
DataSet ds = new DataSet();            
conn.Open();
adapter.Fill(ds);
conn.Close();
Prayas Tiwari
  • 141
  • 1
  • 4
0

Try this it will work with \ escape sequence.

string sqlQuery = "select * from TableName WHERE Name ='McNaught\"s'";
Bharat
  • 2,441
  • 3
  • 24
  • 36