Why won't RODBC upload a dataframe to SQL Server?

余生长醉 提交于 2019-12-08 21:04:15

问题


library(RODBC)
con <- odbcDriverConnect("driver=SQL Server; server=name")
df <- data.frame(a=1:10, b=10:1, c=11:20)

Trying to upload the dataframe:

sqlSave(con, df, tablename='[MyDatabase].[MySchema].[MyTable]', rownames=F)

>Error in sqlColumns(channel, tablename) : ‘MyDatabase.MySchema.MyTable’: table not found on channel

..alternatively creating the table first and then appending to it:

cmd <- "create table [MyDatabase].[MySchema].[MyTable] ([a]  int, [b] int, [c] int)"
sqlQuery(con, cmd)

sqlSave(con, df, tablename='[MyDatabase].[MySchema].[MyTable]', rownames=F, append=T)

>Error in sqlSave(con, df, tablename = "MyTable", rownames = F, : 42S01 2714 [Microsoft][ODBC SQL Server Driver][SQL Server]There is already an object named MyDatabase.MySchema.MyTable in the database. [RODBC] ERROR: Could not SQLExecDirect 'CREATE TABLE MyDatabase.MySchema.MyTable ("a" int, "b" int, "c" int)'

What am I doing wrong?


回答1:


If I add brackets I also get an error.

If I use a connection string with the database to make sure that I am in the correct database (not master) and execute the statement sqlSave(con, df, tablename='dbo.MyTable4', rownames=F) or sqlSave(con, df, tablename='MyTable5', rownames=F) it works.




回答2:


When connecting to a Microsoft SQL Server, it is essential to use odbcDriverConnect instead of odbcConnect in order to perform sqlSave statements etc. Only odbcDriverConnect allows to specifiy a specific database in the connection string.




回答3:


RODBC looks at the default folder for the ODBC server connection to see if you have write permissions there (even if you are going for a subdirectory). If you don't have master permissions, then it fails.

I had to create two connections within R, one for reading from the master and one for writing to my temp directory. These were set by creating two server connections using my local computer's ODBC Administration (within Win7):

-One that defaults to the write-protected master server directory and that I use to pull read-only data.

-One that defaults to the server directory that I have write/drop permissions to.

In other words, your problem is solved by changing your machine's ODBC connection and having R point to the new server connection you will make (the one that defaults to your write-permissioned table.



来源:https://stackoverflow.com/questions/14354801/why-wont-rodbc-upload-a-dataframe-to-sql-server

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