Solved

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

Posted on 2014-07-22
2
402 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

NEW Veeam Agent for Microsoft Windows

Backup and recover physical and cloud-based servers and workstations, as well as endpoint devices that belong to remote users. Avoid downtime and data loss quickly and easily for Windows-based physical or public cloud-based workloads!

Question has a verified solution.

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

JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
Via a live example, show how to setup several different housekeeping processes for a SQL Server.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

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