【问题标题】:Pass R Vector to Sql query将 R 向量传递给 Sql 查询
【发布时间】:2018-05-29 18:30:24
【问题描述】:

我正在使用 RODBC 包访问我在 R 中的 sql 数据库。我无法找到有关如何将向量从 R 传递到 sql 作为向量的任何有用信息。

    id <- ('00003', '00100')
    query <- sqlQuery(channel = channel, query = "select *
                  from prod_cust_vw.store_dim
                  where store_num in id")

我想将 id 向量传递给 sql,而不是对其进行硬编码。

【问题讨论】:

  • 使用pastesprintfpaste("select * from prod_cust_vw.store_dim where store_num in", id)

标签: sql r rodbc


【解决方案1】:

1) sprintfid 转换为适合包含在SQL 语句中的字符串,然后使用sprintf 将其插入到sql 字符串中参见?sprintf

id <- c('00003', '00100')
idString <- toString(sprintf("'%s'", id))  # "'00003', '00100'"
sql_fmt <- "select * from prod_cust_vw.store_dim where store_num in (%s)"
sql <- sprintf(sql_fmt, idString)
sql
## [1] "select * from prod_cust_vw.store_dim where store_num in ('00003', '00100')"

2) fn$ 或使用 gsubfn 包中的 fn$。在 sqlQuery(或任何 R 函数)前面加上 fn$ 会导致扫描实际参数并将 $variables 替换为其内容(其中变量名称应仅包含字母和数字,以便区分它们和其他字符串)。见?fn

library(gsubfn)

fn$sqlQuery(channel = channel, query = "select *
       from prod_cust_vw.store_dim
       where store_num in ($idString)")

【讨论】:

    【解决方案2】:

    我就是这样做的。

    library("RODBC")
    
    
    dbhandle <- odbcDriverConnect('driver={SQL Server};server=Your_Server_Name;database=Your_Database_Name;trusted_connection=true')
    
    currTableSQL<-paste("SELECT * FROM Your_Table",sep="")
    
    currTableDF<-sqlQuery(dbhandle,currTableSQL)
    

    【讨论】:

      【解决方案3】:

      我想尝试弄清楚如何使用 R Notebook SQL 块执行此操作,但无法弄清楚。我在使用其他方法时遇到了很多麻烦。这对我有用。

      library(RODBC)
      myconn<-odbcConnect(dsn = "Data Source Name", 
                      uid = rstudioapi::askForPassword("User ID"), 
                      pwd = rstudioapi::askForPassword("Database password"))
      
      id<-('00003', '00100') # vector of ID's
      
      id<-paste0(personid, collapse = ", ") #create string for entry into query
      
      query<-paste("select *
                    from prod_cust_vw.store_dim
                    where store_num in (", id,")", sep = "") #query -- use "paste". I have not tried with "paste0")
      
      data<-sqlQuery(myconn,query)    #obtain the data by applying the query through the connection.
      

      【讨论】:

      • 不清楚“personid”对象来自哪里以及它包含什么:/
      【解决方案4】:

      新的dbplyr 包对此提供了最佳答案。它允许使用任何 R 对象,并自动将其转换为 SQL

      https://db.rstudio.com/dplyr/

      【讨论】:

        猜你喜欢
        • 2011-05-18
        • 2019-02-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-21
        • 2019-11-03
        相关资源
        最近更新 更多