I have a situation where I created a loop to makes multiple inserts. However, white space is giving an error when making the SQL statement. Example below:
The code below works
query <- "INSERT INTO TBPPRODU (TBPCODIGO,PROCODIGO) VALUES (30084,'LD1268')"
dbSendQuery(con,query)
This does not work
prod <- data.frame(PROCODIGO=c("LD1268","LD1269","LD1270")
x <- data.frame(PROCODIGO=NA)
for (i in 1:nrow(prod)) {
x[i,] <- prod[i,]
query <- paste("INSERT INTO TBPPRODU (TBPCODIGO,PROCODIGO) VALUES (30084,'",x[i,"PROCODIGO"],"')",collapse = "")
dbSendQuery(con,query)
}
## the error output says there is white space before ' LD1268'
Error: nanodbc/nanodbc.cpp:1655: 23000: [ODBC Firebird Driver][Firebird]violation of FOREIGN KEY constraint "PRODU_TBPPRODU" on table "TBPPRODU"
Foreign key reference target does not exist
Problematic key value is ("PROCODIGO" = ' LD1268')
I have tried to trim but is not working as well
query <- paste("INSERT INTO TBPPRODU (TBPCODIGO,PROCODIGO) VALUES (30084,'",x[trimws(i),"PROCODIGO"],"')",collapse = "")
What I am doing wrong?