title: Error in result_create(conn@ptr, statement) : near "(": syntax error in R
body: <p>My post similar with this
  <a href="https://stackoverflow.com/questions/51972937/sqlite-in-r-error-in-result-createconnptr-statement-near">SQLite in R - error in result_create(conn@ptr, statement) : near &quot;)&quot;</a>
  but desicion doesn't work</p>
  
  <pre><code>library("RODBC")
  library("sqldf")
  library("dplyr")
  
  #connect to sql
  
  dbHandle &lt;- odbcDriverConnect("driver={SQL Server};server=MYNAME;database=AOtest;trusted_connection=true")
  
  sql &lt;- paste0 ("select * from  [AOtest].dbo.basisload1
  
  
                 order by doc_date") 
  
  ao &lt;- sqlQuery(dbHandle, sql)
  
  
  
  sqldf(";With CTE
  AS
  (
    select *,
    row_number() over (partition by [product_id],shop_code order by [doc_date])-row_number() over (partition by [product_id],shop_code,mark_1 order by [doc_date]) as grp
    from ao
  ),
  CTE1
  AS
  (
    SELECT *
      FROM CTE c
    OUTER APPLY
    (
      SELECT TOP 1 grp as prvgrp
      FROM CTE
      WHERE mark_1 = 0
      AND doc_date &lt;= c.doc_date
      and [product_id] = c.[product_id]
      and shop_code = c.shop_code
      ORDER BY doc_date DESC
    ) prev
    OUTER APPLY
    (
      SELECT TOP 1 grp as nxtgrp
      FROM CTE
      WHERE mark_1 = 0
      and [product_id] = c.[product_id]
      and shop_code = c.shop_code
      AND doc_date &gt;= c.doc_date
      ORDER BY doc_date 
    ) nxt
  )
  
  SELECT c.product_id,c.shop_code,c.doc_date,c.ship_count,c.mark_1,case when med &lt; ship_count then med when ship_count &lt; 0 then 0 else ship_count end as output,
  c.ship_count - case when med &lt; ship_count then med when ship_count &lt; 0 then 0 else ship_count end as output1
  into test2
  FROM CTE1 c
  OUTER APPLY (
    SELECT MAX(med) AS med
    FROM
    (
      SELECT PERCENTILE_DISC(0.5) WITHIN GROUP(ORDER BY CASE WHEN ship_count &lt;= 0 THEN 0 ELSE ship_count END) OVER (PARTITION BY [product_id],shop_code,grp) AS med
      FROM CTE
      WHERE grp IN (nxtgrp,prvgrp)
      and [product_id] = c.[product_id]
      and shop_code = c.shop_code
    )r
  )c2
  order by doc_date")
  </code></pre>
  
  <p>so the error</p>
  
  <pre><code>Error in result_create(conn@ptr, statement) : near "(": syntax error
  </code></pre>
  
  <p>How to avoid this error in my case.
  Of course i could run this code from SQL Server Management Studio, but server where installed sql, all the time busy by other experts and other tasks, on my server only R.</p>