Using Single Quotes in a dynamic SQL

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • SnehaAgrawal
    New Member
    • Apr 2009
    • 31

    #1

    Using Single Quotes in a dynamic SQL

    Hi I want to know how can we use single quotted string as a part of dynamic sql
    Consider the following code

    exec('select branchid from '+@tablename+' where Entrystatus='NE W' AND BranchName= '+@branchname')
    In the above query New is string like 'NEW'and BranchName is also a string so how am I suppose to write single quotes?
    wht is the main funda behind using them?
    thnks
  • Uncle Dickie
    New Member
    • Nov 2008
    • 67

    #2
    Does this article help?

    Comment

    • jvskarthick
      New Member
      • Nov 2006
      • 13

      #3
      exec('select branchid from '+@tablename+' where Entrystatus=''N EW'' AND BranchName= '+@branchname')

      Just change 'NEW' to ''NEW'' and try it...

      Reg,
      JK

      Comment

      • Delerna
        Recognized Expert Top Contributor
        • Jan 2008
        • 1134

        #4
        [code=sql]
        exec(
        'select branchid
        from '+@tablename+'
        where Entrystatus=' + char(39)+'NEW' +char(39) +'
        AND BranchName= '+ char(39) + @branchname + char(39)
        )
        [/code]

        or this might look cleaner to read
        [code=sql]

        declare @New
        set @New=char(39) + 'NEW' + char(39)
        set @branchname=cha r(39) + @branchname + char(39)
        exec('select branchid from ' + @tablename + ' where Entrystatus=' + @New +' AND BranchName= ' + @branchname)
        [/code]

        39 is the ASCII code for a single quote

        Comment

        • Delerna
          Recognized Expert Top Contributor
          • Jan 2008
          • 1134

          #5
          and as Uncle dickie highlights

          this
          select 'test '''+'hello'+''' test'

          also works
          interresting !

          Comment

          • SnehaAgrawal
            New Member
            • Apr 2009
            • 31

            #6
            thnks for the solution

            Comment

            Working...