locked
escape character for single quote RRS feed

  • Question

  • I have below sql query embedded in c# function where input is ID

    sb.Append("Select Namee ");
             sb.Append("FROM [");
             sb.Append("EmpData");
             sb.Append("].[dbo].[Employee]");

             sb.Append("WHERE [EmpCode] =");
             sb.Append("' + ID + '");

    But the problem is '344354' getting converted  &quote; 344354 &quote; and query is failing to execute.

    Please let me know your suggestions.

    Thanks in Advance

    Monday, January 9, 2012 6:12 PM

Answers

  • I suggest to use parameters, e.g.

    sb.Append("SELECT Name FROM EmpData.dbo.Employee WHERE EmpCode = @ID")

    and then also use parameters properly in your code. This will be a safe approach and everything else is not safe and should not be used unless forced to under a gun.


    For every expert, there is an equal and opposite expert. - Becker's Law


    My blog
    • Proposed as answer by Brian Tkatch Tuesday, January 10, 2012 3:31 PM
    • Marked as answer by KJian_ Monday, January 16, 2012 8:41 AM
    Monday, January 9, 2012 6:14 PM

All replies

  • It's chr(34) or something like that...for string concatenation. You'll have to google the Chr()'s
    Already reported as abusive
    Monday, January 9, 2012 6:13 PM
  • I suggest to use parameters, e.g.

    sb.Append("SELECT Name FROM EmpData.dbo.Employee WHERE EmpCode = @ID")

    and then also use parameters properly in your code. This will be a safe approach and everything else is not safe and should not be used unless forced to under a gun.


    For every expert, there is an equal and opposite expert. - Becker's Law


    My blog
    • Proposed as answer by Brian Tkatch Tuesday, January 10, 2012 3:31 PM
    • Marked as answer by KJian_ Monday, January 16, 2012 8:41 AM
    Monday, January 9, 2012 6:14 PM
  • I fully agree with Naomi. Dan Guzman has a good blog post about this: http://weblogs.sqlteam.com/dang/archive/2008/02/18/Why-Parameters-are-a-Best-Practice.aspx
    Tibor Karaszi, SQL Server MVP | web | blog
    Monday, January 9, 2012 7:15 PM