R中RODBC查询的正确语法是什么

时间:2016-11-04 09:58:54

标签: sql r ms-access

我正在尝试使用以下代码在R中使用RODBC查询Access数据库:

library(RODBC)
channel <- odbcConnectAccess("S:\\mypath\\PhysiPopDONOTTOUCH\\Physiology.mdb")

data <- sqlQuery( channel , paste ("select Endoscopy.*,
Histology.Diagnosis from Endoscopy JOIN PatientData ON
Endoscopy.HospNum_Id=PatientData.HospNum_Id  JOIN Histology ON
Histology.HospNum_Id=PatientData.HospNum_Id WHERE histology.VisitDate
= Endoscopy.VisitDate"))

。这不成功,因为我收到错误:

[1] "42000 -3506 [Microsoft][ODBC Microsoft Access Driver] Syntax
error in FROM clause."
[2] "[RODBC] ERROR: Could not SQLExecDirect 'select Endoscopy.*,
Histology.Diagnosis from Endoscopy JOIN PatientData ON
Endoscopy.HospNum_Id=PatientData.HospNum_Id  JOIN Histology ON
Histology.HospNum_Id=PatientData.HospNum_Id WHERE Histology.VisitDate
= Endoscopy.VisitDate'"

EndoscopyHistologyPatientData表各有一对一。我在语法上做错了什么?

1 个答案:

答案 0 :(得分:1)

MS Access SQL要求JOIN配对括在括号中。此外,使用paste()是为了消除在R中断行时出现的字符串值内的长空格。并考虑使用表别名来简明地引用表。也包括一个分号终止符(参见:When should I use semicolons in SQL Server?)。见下面的调整:

data <- sqlQuery(channel , 
                 paste("SELECT e.*, h.Diagnosis",
                       "(FROM PatientData p"
                       "INNER JOIN Endoscopy e p ON e.HospNum_Id = p.HospNum_Id)",
                       "INNER JOIN Histology h ON h.HospNum_Id = p.HospNum_Id",
                       "WHERE h.VisitDate = e.VisitDate;", sep=" "))