Search code examples
rcreate-table

R DBI dbSendStatement not working for CREATE TABLE


Reading through the reference material- https://dbi.r-dbi.org/reference/dbSendStatement.html

Is there are reason the below code doesn't create the temp table?:

if (!require("pacman")
) install.packages("pacman")

pacman::p_load(
  #add list of libraries here
  DBI,
  odbc,
  RODBC,
  stringr
)

DBI:dbSendStatement(con, "CREATE TABLE #SURGEONS(PROV_ID VARCHAR(18),PROV_NAME VARCHAR(123),SERV_NAME VARCHAR(9));")

When I run the below:

DBI::dbGetQuery(con, "SELECT * FROM #SURGEONS")

It errors out with: Invalid object name '#SURGEONS'

But when I feed it into dbCreateTable it works?

dbCreateTable(
  conn = con,
  name = "#SURGEONS",
  fields = c(
    PROV_ID = "VARCHAR(18)",
    PROV_NAME = "VARCHAR(123)",
    SERV_NAME = "VARCHAR(9)"
    ),
  temporary = TRUE
  )

And I run:

DBI::dbGetQuery(con, "SELECT * FROM #SURGEONS")

Then I don't get an error that the table wasn't created-

[1] PROV_ID   PROV_NAME SERV_NAME
<0 rows> (or 0-length row.names)

Solution

  • Roland answered in the comment-

    Need to use dbExecute in this case and not dbSendStatement