SAA
SAA

Reputation: 21

SQL Query with single quotes retrieves no record

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();

Upvotes: 0

Views: 115

Answers (3)

Kashish Agarwal
Kashish Agarwal

Reputation: 333

Please try this:

string sqlQuery = 'SELECT * FROM TableName WHERE Name ="McNaught\'s"'

Upvotes: 2

Bharat
Bharat

Reputation: 2464

Try this it will work with \ escape sequence.

string sqlQuery = "select * from TableName WHERE Name ='McNaught\"s'";

Upvotes: 0

Prayas Tiwari
Prayas Tiwari

Reputation: 141

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();

Upvotes: 0

Related Questions