Save or Read data from SQL Server in to R using ODBC package

末鹿安然 提交于 2021-01-29 08:24:43

问题


If I want to connect R to a database, do I still need to install driver for R user?

I had done successful connection with server but unable to read/write/fetch the tables.

library(odbc)
con <- dbConnect(odbc::odbc(), 
         .connection_string = 'driver={SQL Server};server=DW01;database=AF_DW;trusted_connection=true')

Now I can see AF_DW in RStudio connections.

dbListFields(con, "Visits")

I can see all the variables in the table "Visits"

data <- dbReadTable(con, "Visits")

Got an Error: nanodbc/nanodbc.cpp:1655: 42000: [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name 'Visits'. [Microsoft][ODBC SQL Server Driver][SQL Server]Statement(s) could not be prepared. 'SELECT * FROM "Visits")

data3 <- dbGetQuery(con, "SELECT * FROM Visits")

Got same error

data4 <- dbSendQuery(con, "SELECT * FROM Visits")

Got same error

con_in_R <- dbFetch(dbSendQuery(con,"SELECT * FROM Visits"))

Error in (function (cond) : error in evaluating the argument 'res' in selecting a method for function 'dbFetch': nanodbc/nanodbc.cpp:1655: 42000: [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name 'Visits'. [Microsoft][ODBC SQL Server Driver][SQL Server]Statement(s) could not be prepared. 'SELECT * FROM Visits'

Appreciate your help. Thank you.


回答1:


According to you image, Visits is not stored in the default dbo schema as all your queries assume but under the eCW schema.

Like most RDBMS's, SQL Server follows the three part name convention for objects (tables, stored procedures, functions): [database].[schema].[object] where database is not necessary for a database specific connection and schema not necessary for dbo default.

Therefore, you need to reference schema and table name in your attempted queries.

s <- Id(schema = "eCW", table = "Visits")

# READ FROM NON-DEFAULT SCHEMA TABLE
data3 <- dbReadTable(con, s) 
data3 <- dbGetQuery(con, "SELECT * FROM [eCW].[Visits]")

# WRITE TO NON-DEFAULT SCHEMA TABLE
dbWriteTable(conn, s, mydataframe)
dbWriteTable(con, SQL("eCW.Visits"), mydataframe)


来源:https://stackoverflow.com/questions/65014679/save-or-read-data-from-sql-server-in-to-r-using-odbc-package

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!