In case someone else comes across this SO question....
I also was having a problem with the using the SELECT * FROM table
statement with a setup like this:
library(odbc)
library(DBI)
con <- DBI::dbConnect(odbc::odbc(),
Driver = "SQL Server",
Server = "CorporateServer",
Database = "DB_of_Interest",
Port = 1433)
sql <- "SELECT TOP (10) *
FROM [DB_of_Interest].[dbo].[tb_of_interest]"
dbGetQuery(con, sql)
Which generated this error:
Error in result_fetch(res@ptr, n) :
nanodbc/nanodbc.cpp:3069: 07009: [Microsoft][ODBC SQL Server Driver]Invalid Descriptor Index
Warning message:
In dbClearResult(rs) : Result already cleared
My Solution
After looking at RStudio -- Connect to a Database, I looked to see what other drivers might be available to me:
sort(unique(odbcListDrivers()[[1]]))
[1] "Amazon Redshift (x64)"
[2] "Hortonworks Hive ODBC Driver"
[3] "Hortonworks Spark ODBC Driver"
[4] "Microsoft Access Driver (*.mdb, *.accdb)"
[5] "Microsoft Access Text Driver (*.txt, *.csv)"
[6] "Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)"
[7] "MySQL ODBC 5.3 ANSI Driver"
[8] "MySQL ODBC 5.3 Unicode Driver"
[9] "ODBC Driver 17 for SQL Server"
[10] "PostgreSQL ANSI(x64)"
[11] "PostgreSQL Unicode(x64)"
[12] "Simba ODBC Driver for Google BigQuery"
[13] "SQL Server"
[14] "SQL Server Native Client 11.0"
And #9 caught my eye: ODBC Driver 17 for SQL Server
. I went into the Windows Control Panel, and set up a new ODBC Data Source using that particular driver (in my case, I named it "Buyer Central 2" and I have Integrated Windows authentication, so no username/password), and then revised my R code to be:
con2 <- DBI::dbConnect(odbc::odbc(),
dsn = "Buyer Central 2")
dbGetQuery(con2, sql)
Now the sql statement with the glob (*) works for me.
Alternative that doesn't work (for me)
I thought and tried to use the other ODBC driver without the formal setup in the data source administrator:
con3 <- DBI::dbConnect(odbc::odbc(),
Driver = "ODBC Driver 17 for SQL Server",
Server = "CorporateServer",
Database = "DB_of_Interest",
Port = 1433)
But that line fails for me with the following:
Error: nanodbc/nanodbc.cpp:1021: 01S00: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user ''. [Microsoft][ODBC Driver 17 for SQL Server]Invalid connection string attribute
I searched for a reason why it works when set up in admin tools, but not as above, and found comments related to SQL Server 2014 not working with this driver due to SSL issues, but I checked my version and I'm using SQL Server 2016... so not that. Curious why it doesn't work this way, but the above solution does work.
dbFetch()
, does rs come through as a dataframe? – MacswandbGetQuery() ... calls 'dbSendQuery()', then 'dbFetch()', ensuring that the result is always free-d by 'dbClearResult()'
. – Distributive