title: Use Open Query with quoted items
body: <p>I am trying to use openquery to access a linked server. However, it appears to be impossible because, you cannot have the correct number of Single quotes. I need to pass a variable Start and End date, so I cannot use the basic openquery method, but instead must use the EXEC(@OPENQUERY+ @SQL) method. The problem is, to pass the date through the @SQL variable I must use ''' so it has 1 quote, but then when it gets passed to the EXEC(OPENQUERY+@SQL) the open query which introduces another level of quotes, causes the dates to now be not be quoted and I get an error. If I add another layer of quotes it then causes them to be double quotes causing that error. Is it not possible to use quotes in an open query? I have the same issue even passing things like Where Username = 'Jack'. I can never have the correct number of quotes.</p>
  
  <pre><code>DECLARE @STARTDT NVARCHAR(10) = '2019-01-01'
          ,@ENDDT NVARCHAR(10) = '2019-03-01'
  
  DECLARE @SQL NVARCHAR(4000)
  DECLARE @OPENQUERY nvarchar(4000)
          , @LinkedServer nvarchar(4000)
  
  SET @LinkedServer = 'ProductionSvr'
  
  SET @SQL =
  'select  *
  from SalesData a
  where a.Sale_date between ''' + @StartDt + ''' and ''' + @ENDDT + ''')
  '''
  
  print @SQL
  
  SET @OPENQUERY = 'SELECT * FROM OPENQUERY('+ @LinkedServer + ','''
  
  EXEC (@OPENQUERY+@SQL)
  </code></pre>