Skip to content

Instantly share code, notes, and snippets.

@jeremyyeo
Created November 27, 2016 20:46
Show Gist options
  • Save jeremyyeo/71db9314d0628bf79a8ca8bb4e22e369 to your computer and use it in GitHub Desktop.
Save jeremyyeo/71db9314d0628bf79a8ca8bb4e22e369 to your computer and use it in GitHub Desktop.
For inserting SQL NULLs for variables in R that are NA
require(RODBC)
con <- odbcConnect("dsn")
clean <- function(x) {
if (is.character(x)) {
out <- paste0("'", x, "'")
} else if (is.na(x)) {
out <- "NULL"
} else {
out <- x
}
if (out == "'NA'") {
out <- "NULL"
}
return(out)
}
for (i in 1:2) {
val1 <- clean(x[i, 1])
val2 <- clean(x[i, 2])
val3 <- clean(x[i, 3])
query <-
paste(
"INSERT INTO db.schema.table VALUES(",
val1,
",",
val2,
",",
val3,
")"
)
sqlQuery(con, query, as.is = T)
}
odbcClose(con)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment