2016-08-05 63 views
-1

我在SQL服務器中有一個大表,並希望在日期使用WHERE子句導入到R中。從SQL服務器過濾並讀取數據集到R

library(RODBC) 
dbhandle <- odbcDriverConnect('driver={SQL Server};server=mysqlhost;database=mydbname;trusted_connection=true') 

# Main table query works well 
res <- sqlQuery(dbhandle, 'select * from Main') 

# I would like to filter it by date column 
res <- sqlQuery(dbhandle, 'select * from Main where Date > '2010-01-01'') 
+1

您可能遇到單引號問題。你必須逃避它們。您的查詢沒有任何問題@Prasanth – MaxPD

+0

或在外部使用雙引號:'「select * from Main where Date>'2010-01-01';'' – SymbolixAU

+0

您可能還需要使用'[Date]' 。我相信日期是SQL中的保留字。 – Benjamin

回答

1

嘗試使用的SQLQuery(數據庫句柄, 'SELECT * FROM主那裏日期> 「 ' 」2010-01-01「'」')就可以避免處理引號

1

一種方法是使用參數化查詢。

library (RODBCext) 
sqlExecute (
    dbhandle, 
    'select * from Main where [Date] > ?', 
    list (date = '2010-01-01'), 
    fetch = TRUE, 
    stringsAsFactors = FALSE 
) 
相關問題