Created
November 27, 2016 20:46
-
-
Save jeremyyeo/71db9314d0628bf79a8ca8bb4e22e369 to your computer and use it in GitHub Desktop.
For inserting SQL NULLs for variables in R that are NA
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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