title: Escape single quote in openquery using dynamic query
body: <p>I need to retrieve data from a linked server using a parameter, @PickedDate for example. The query works fine if I skip @A and @B, but it always returns an error due to a missing single quote. Please advise, thanks.</p>
  
  <p>The query:</p>
  
  <pre><code>Declare @OPENQUERY nvarchar(500), @TSQL nvarchar(max), @LinkedServer nvarchar(20), @A varchar(5), @B varchar(5), @PickedDate varchar(8)
  Set @PickedDate = '20150501'
  Set @A = 'AAA'
  Set @B = 'BBB'
  Set @LinkedServer = 'LinkedServerName'
  Set @OPENQUERY = 'Select * From Openquery('+ @LinkedServer + ','''
  Set @TSQL = 'SELECT cases.casenum, user.username, code
              From cases
              Inner join user
              On cases.casenum = user.user_id
              Where cases.date_opened &gt; DateAdd(day,1-datepart(dw,Convert(date,' + @PickedDate + ')), Convert(date,' + @PickedDate + '))
              And cases.date_opened &lt;= DateAdd(day,8-datepart(dw,Convert(date,' + @PickedDate + ')), Convert(date,' + @PickedDate + '))
              And cases.code IN (' + @A +', ' + @B + ')
              ORDER BY casenum'')'
  Exec (@Openquery+@TSQL)
  </code></pre>
  
  <p>OLE DB provider "MSDASQL" for linked server "LinkedServerName" returned message "[Sybase][ODBC Driver][SQL Anywhere]Column 'AAA' not found".
  Msg 7321, Level 16, State 2, Line 1
  An error occurred while preparing the query "</p>
  
  <pre><code>  SELECT cases.casenum, username, code
    From cases
    Inner join user
    On cases.casenum = user.user_id
    Where cases.date_opened &gt; 
      DateAdd(day,1-datepart(dw,Convert(date,20150501)), Convert(date,20150501))
    And cases.date_opened &lt;= 
      DateAdd(day,8-datepart(dw,Convert(date,20150501)), Convert(date,20150501))
    And cases.code IN (AAA, BBB)
    ORDER BY casenum" 
  </code></pre>
  
  <p>for execution against OLE DB provider "MSDASQL" for linked server "LinkedServerName". </p>