As source code shows, RODBC::sqlUpdate()
cleans column names of special characters (non-alphanumeric characters) with a mangleColNames()
function:
mangleColNames <- function(colnames) gsub("[^[:alnum:]_]+", "", colnames)
Which removes any spaces as seen here:
colnames <- "First Name"
mangleColNames <- function(colnames) gsub("[^[:alnum:]_]+", "", colnames)
mangleColNames(colnames)
# [1] "FirstName"
To resolve, consider one of three options:
Update the source code of your RODBC library package to comment out mangleColNames()
call in sqlUpdate
. Specifically, use the approach below as shown here.
trace("sqlUpdate", edit=TRUE)
However, above is a temporary, interactive fix for your current R session. You will need to go to underlying library package code to adjust it permanently. Do note: as changing any code there is possibility of side effects can occur. Tread cautiously with this approach.
In fact, you may still need to add a wrapper to handle such spaces and special characters. In MS Access, you would use square brackets or backticks to work with such names.
Update column names in MS Access with DDL commands passed in sqlQuery
. By the way, like all DBMS's it is highly recommended not to use spaces, special characters, or reserved keywords in names of columns, tables, views, or other stored objects.
ALTER TABLE mytable ALTER COLUMN fieldname fieldtype
Which for you would do as the following and can be looped to update all columns:
# ADD NEW COLUMN
sqlQuery(channel, "ALTER TABLE mytable ADD COLUMN [FirstName] Text(255)")
sqlQuery(channel, "UPDATE mytable SET [FirstName] = [First Name]")
# DROP OLD COLUMN
sqlQuery(channel, "ALTER TABLE mytable DROP COLUMN [First Name]")
Use a different library such as the R DBI-complaint, odbc
, which does not have sqlUpdate
but can be accommodated with dbWriteTable()
without assumptions of column names.