Search code examples
sql-serverrrodbc

SQL Server query failed with RODBC connection, works in SQL Server


Hello and thanks in advance.

I'm using the R package RODBCto connect to a SQL Server database and run a query to DELETE data in a table. When I run other queries like SELECT statements etc... the query runs fine or at least I get a detailed error. The query below doesn't give much more than a failure"

bulk <- odbcConnect(dsn="DSN", uid = "UID", pwd = "PWD",case="nochange", colQuote=c(), tabQuote=c() )

prodnum <- 9803

  sqlQuery(bulk,
           paste("DELETE FROM [schema].[table] WHERE date = (SELECT DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)) AND ID IN ('"
                  ,prodnum
                  ,"')"
                  , sep=""), believeNRows=FALSE)

I've asked others to run the query through SQL Server using my credentials and it seems to work fine for them. R just returns this error:

[1] "[RODBC] ERROR: Could not SQLExecDirect 'DELETE FROM [schema].[table] WHERE date = (SELECT DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)) AND ID IN ('9803)'"

Solution

  • Turns out that if there is no data in the table, that error will return. I inserted some data into the table then tried running the delete query after. Worked 100% of the time.