Solved

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

Posted on 2014-07-22
2
390 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:Serversys
2 Comments
 
LVL 52

Accepted Solution

by:
Carl Tawn earned 500 total points
Comment Utility
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:Serversys
Comment Utility
Perfect. Simples !!
Thanks
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Suggested Solutions

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.

728 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now