简体   繁体   中英

How does one write to a SQL Server table with specific schema from R using DBI?

I am having trouble using dbWriteTable to output my dataframe to a SQL Server table. I can do it when the schema is default but not if I try to use an alternate schema. See below:

# Before running this example, create the table in SQL Server via
# CREATE TABLE [guest].[MikeTestTable](
# [a] [float] NULL,
# [b] [float] NULL,
# [c] [varchar](255) NULL)

# df to insert
df <- data.frame(a=c(10,20,30),
                 b=c(20,40,60),
                 c=c('oneT','twoT','threeT'))

# connection string
MSSQLConnectionString <- '
  driver={SQL Server};
  server=localhost;
  database=SAM;
  trustedConnection=true;
  '

# DBI connection
con <- DBI::dbConnect(odbc::odbc(),
                      .connection_string = MSSQLConnectionString)

# query to read from table
q <- "SELECT [a]
,[b]
,[c]
FROM HCRWriteData"

# get data
dfOut <- DBI::dbGetQuery(con, q)

head(dfOut)
 > [1] a b c
 > <0 rows> (or 0-length row.names)

# now try to write contents of df to the table.
# this table uses the default schema.
DBI::dbWriteTable(conn = con, 
                  name = 'HCRWriteData', 
                  value = df,
                  append = TRUE)

# get data after writing
dfOut <- DBI::dbGetQuery(con, q)
head(dfOut
     > a  b      c
     > 1 10 20   oneT
     > 2 20 40   twoT
     > 3 30 60 threeT

### Using non-default schema
# query to read from table
q2 <- "SELECT [a]
,[b]
,[c]
FROM [SAM].[guest].[MikeTestTable]"

# get data
dfOut <- DBI::dbGetQuery(con, q2)
head(dfOut)
     > [1] a b c
     > <0 rows> (or 0-length row.names)

#Finally, writing to the non-default schema:
# this table uses a non-default schema
DBI::dbWriteTable(conn = con, 
                  name = 'guest.MikeTestTable', 
                  value = df,
                  append = TRUE)

# get data
dfOut <- DBI::dbGetQuery(con, q2)
head(dfOut)
     >  Error: Table guest.MikeTestTable does not exist

I can read from either table, but only write to a default schema.

Try using SQL like this:

dbWriteTable(con, SQL('guest.MikeTestTable'), df, append = TRUE)

See last example here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM