SQL Server Schemas & R Tip

October 19, 2019
DBI odbc SQL Server R

I ran into an issue the other day where I was tring to write a new table to a SQL Server Database with a non-default schema. I did end up spending a bit of time debugging and researching so I wanted to share for anyone else that runs into the issue. Using the DBI::Id function, allows you to specify the schema when you are trying to write a table to a SQL Server database.

DBI::dbWriteTable(con, 
                  DBI::Id(schema = "schema", table = "tablename"), 
                  df)

But the code above will return a strange error:

After some investigation I found a workaround to be able to write the table. For non-default schemas, a “_” needs to in the table name for it to work.

DBI::dbWriteTable(con, 
                  DBI::Id(schema = "schema", table = "tablename_"), 
                  df)

This really isn’t ideal for naming conventions so using the t-sql command sp_rename will rename the table to what I originally wanted.

DBI::dbWriteTable(con, 
                  DBI::Id(schema = "schema", table = "tablename"), 
                  df)
DBI::dbGetQuery(con, "USE database;
EXEC sp_rename '[schema].[tablename_]', 'tablename';")

I ran into the same issues for overwriting tables as well but a workflow for doing the same is simply to use sp_rename a couple of times.

DBI::dbGetQuery(con, "USE database;
EXEC sp_rename '[schema].[tablename]', 'tablename_';")
DBI::dbWriteTable(con, 
                  DBI::Id(schema = "schema", table = "tablename_"), 
                  df, 
                  overwrite = TRUE)
DBI::dbGetQuery(con, "USE database;
EXEC sp_rename '[schema].[tablename_]', 'tablename';")

Setting Up Raspberry Pi Temperature/Humidity Sensors for Data Analysis in R

February 21, 2019
R DBI ggplot2 RMariaDB Raspberry Pi bash MYSQL

Shiny App: Drive Time Isochrones

November 5, 2018
sf leaflet osrm viridis shiny geospatial R

Introduction to Geospatial Analysis in R

September 30, 2018
R geospatial sf shiny raster sp ggplot2 leaflet osrm httr rvest