Solved

C# code with a SQL string is converting single quotes to 2 single quotes.

Posted on 2014-07-22
2
397 Views
Last Modified: 2014-07-23
I have a bit of code as below, and for some strange reason the actual code issued to SQL server has all of the single quotes replaced with 2x single quotes. Not by my code though. Any thoughts anyone ?
C# code
string sql = @"SELECT TOP 1 isnull(rtrim(JCI.joco_FirstName), '''' ) WHERE Case_CaseId = @CaseId;";
     // execute
     using (SqlDataAdapter da = new SqlDataAdapter(sql.ToString(), connection))
     {
         da.SelectCommand.Parameters.AddWithValue("@CaseId", JobId);
         da.Fill(dtDetail);
     }


Actual SQL issued (via SQL Profiler trace)
exec sp_executesql N'SELECT TOP 1 isnull(rtrim(JCI.joco_FirstName), '''''''' ) WHERE Case_CaseId = @CaseId;',N'@CaseId int',@CaseId=2237361

Open in new window

0
Comment
Question by:Phil Catterall
2 Comments
 
LVL 52

Accepted Solution

by:
Carl Tawn earned 500 total points
ID: 40213622
SQL Server is escaping them because the parameter to sp_executesql is itself wrapped in single quotes. You don't need to double up the quotes in your query, the following should work fine:
string sql = @"SELECT TOP 1 isnull(rtrim(JCI.joco_FirstName), '' ) WHERE Case_CaseId = @CaseId;";

Open in new window

0
 

Author Closing Comment

by:Phil Catterall
ID: 40213944
Perfect. Simples !!
Thanks
0

Featured Post

Three Reasons Why Backup is Strategic

Backup is strategic to your business because your data is strategic to your business. Without backup, your business will fail. This white paper explains why it is vital for you to design and immediately execute a backup strategy to protect 100 percent of your data.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
In this article we will learn how to fix  “Cannot install SQL Server 2014 Service Pack 2: Unable to install windows installer msi file” error ?
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

685 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question