【问题标题】:R- variable in ODBC queryODBC 查询中的 R-变量
【发布时间】:2014-10-15 20:04:20
【问题描述】:

我需要运行多个查询以将数据从 SQL Server 获取到 R 多个时期。我想在 sqlQuery 函数的查询中使用句点作为变量。

我的查询如下:

fld_fec_car<-sqlQuery(dbNGC, "select fld_fec_car 
from neptuno.data_mart.[dbo].[tbl_periodo_asig]
where fld_cod_emp='tg'
and fld_periodo ='072014'")

我也想拥有这样的东西

per='072014'


fld_fec_car<-sqlQuery(dbNGC, "select fld_fec_car 
from neptuno.data_mart.[dbo].[tbl_periodo_asig]
where fld_cod_emp='tg'
and fld_periodo =&per")

是否可以在 sqlQuery 函数中包含变量值?谢谢。

【问题讨论】:

    标签: sql r variables odbc


    【解决方案1】:

    可能有更优雅的解决方案,但我通常做的是创建一个函数来根据输入生成查询文本:

    genQuery <- function(arg)
    {
      lhs <- "select fld_fec_car 
      from neptuno.data_mart.[dbo].[tbl_periodo_asig]
      where fld_cod_emp='tg'
      and fld_periodo ='"
      rhs <- "';"
      ##
      Query <- paste0(lhs,arg,rhs)
      Query <- gsub("\n"," ",Query)
      Query <- gsub("\t"," ",Query)
      return(Query)
    }
    ##
    > genQuery(123)
    [1] "select fld_fec_car   from neptuno.data_mart.[dbo].[tbl_periodo_asig]  where fld_cod_emp='tg'  and fld_periodo ='123';"
    > genQuery(436)
    [1] "select fld_fec_car   from neptuno.data_mart.[dbo].[tbl_periodo_asig]  where fld_cod_emp='tg'  and fld_periodo ='436';"
    

    gsub("\n"," ",...)gsub("\t"," ",...) 只是为了去掉换行符和制表符——我的 SQL 客户端不接受它们;你的可能不一样。

    【讨论】:

      【解决方案2】:

      我用过粘贴:

      a<-paste("SELECT fld_fec_car FROM neptuno.data_mart.[dbo].[tbl_periodo_asig] where fld_cod_emp='tg' and fld_periodo='", per, "'", sep='')
      

      然后

      sqlQuery(dbNGC, a)
      

      【讨论】:

        猜你喜欢
        • 2021-09-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多