简体   繁体   English

如何使用 Postgresql 到 R 中的变量更改 SET 列名称?

[英]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.我在 Postgresql 中有一个分析表,它由几列组成,即 unbonding、clogging 和dirty。 this column contains numbers.此列包含数字。

I want to update a value +1 in the column according to the "issue" selected by the user.我想根据用户选择的“问题”更新列中的值+1。 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?如何根据用户选择的问题更改SET“列名”

thankyou谢谢你

My answer is typically data-binding, using either DBI::dbBind or the params= argument of DBI::dbGetQuery .我的答案通常是数据绑定,使用DBI::dbBindDBI::dbGetQuery ::dbGetQuery 的params=参数。 Unfortunately, that's for data only and doesn't work with identifiers (eg, column names).不幸的是,这仅适用于数据,不适用于标识符(例如,列名)。

One can still use sqlInterpolate , though.不过,仍然可以使用sqlInterpolate 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.这样做的一个风险是命名case :在定义表中的列时,有很多关于区分大小写的建议,一个常见的建议是始终转换为小写。 If the column was actually defined with mixed case, then when you use dbQuoteIdentifier , you must get it exactly right .如果该列实际上是用混合大小写定义的,那么当您使用dbQuoteIdentifier时,您必须完全正确

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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