3

When trying to run an update with a SQL statement with the sqlQuery function in RODBC, it brings up an error

"[RODBC] ERROR: Could not SQLExecDirect '.

How do you run a direct update statement with R?

done_merson
  • 2,800
  • 2
  • 22
  • 30
  • I would recommend using the `odbc` package (based on the DBI spec) which even supports bulk inserts and updates (where `RODBC` is very slow) see https://stackoverflow.com/a/43642590/4468078 – R Yoda Nov 30 '17 at 21:32

1 Answers1

2

You cannot use a plain SQL update statement with the SQL query function, it just needs to return a resultset. For example, the following statement won't work:

sql="update mytable set column=value where column=value"
cn <-odbcDriverConnect(connection="yourconnectionstring")
resultset <- sqlQuery(cn,sql)

But if you add an output statement, the SQL query function will work fine. For example.

sql="update mytable set column=value output inserted.column where column=value"
cn <-odbcDriverConnect(connection="yourconnectionstring")
resultset <- sqlQuery(cn,sql)

I just added a function to make it easy to take your raw sql and quickly turn it into an update statement.

  setUpdateSql <-function(updatesql, wheresql, output="inserted.*"){
   sql=paste(updatesql," output ",output, wheresql)
   sql=gsub("\n"," ",sql) #remove new lines if they appear in sql
   return(sql)

}

So now I just need to split the SQL statement and it will run. I could also add an "inserted.columnname" if I didn't want to return the whole thing.

sql=setUpdateSql("update mytable set column=value","where column=value","inserted.column")#last parameter is optional
cn <-odbcDriverConnect(connection="yourconnectionstring")
resultset <- sqlQuery(cn,sql)

The other advantage with this method is you can find out what has changed in the resultset.

done_merson
  • 2,800
  • 2
  • 22
  • 30
  • THX, save me a lot time to solve the issue. I am using stored procedures normally to update data and SPs can be called via `EXEC` in `sqlQuery`. An alternative would be using the new DBI-based package `odbc` (without "R" in the name!). – R Yoda Nov 30 '17 at 21:26