简体   繁体   中英

How to change SET column name with variable in Postgresql through R?

I have a analytic table in Postgresql which consists of several columns namely, unbonding, clogging and dirty. this column contains numbers.

I want to update a value +1 in the column according to the "issue" selected by the user. For example "clogging".

issue="clogging"
currentdata <- dbGetQuery(con,paste0("SELECT DISTINCT *
                                                FROM analytic
                                                ORDER BY analytic.id DESC
                                                FETCH FIRST 1 ROWS ONLY;"))
issueval <- currentdata[[issue]]

sql <- sqlInterpolate(con, 
                      "UPDATE analytic 
                      SET issue = ?val
                      where id = ?code",
                      code = "ID111",
                      val = issueval+1
)
dbSendQuery(con,sql)

How can I change the SET "column name" according to the issue the user has selected?

thankyou

My answer is typically data-binding, using either DBI::dbBind or the params= argument of DBI::dbGetQuery . Unfortunately, that's for data only and doesn't work with identifiers (eg, column names).

One can still use sqlInterpolate , though. Try this:

issue <- "clogging"
sql <- sqlInterpolate(con, 
                      "UPDATE analytic 
                      SET ?col = ?val
                      where id = ?code",
                      col = dbQuoteIdentifier(con, issue),
                      code = "ID111",
                      val = issueval+1)

One risk of this is that of name case : there are many recommendations on the topic of case-sensitivity when defining columns in a table, with a common recommendation being to always convert to lower-case. If the column was actually defined with mixed case, then when you use dbQuoteIdentifier , you must get it exactly right .

If you run into problems with this and do not want to require that the user get it right all of the time, you could always do something like this:

realfields <- dbListFields(con, "analytic")
issue <- realfields[ match(tolower(issue), tolower(realfields)) ]
# similarly
issue <- grep(paste0("^", issue, "$"), realfields, value = TRUE, ignore.case = TRUE)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM