【问题标题】:Using where clause for R Variable in R script to use it in SQL statement在 R 脚本中为 R 变量使用 where 子句以在 SQL 语句中使用它
【发布时间】:2017-08-07 10:27:00
【问题描述】:

我有两张桌子;即 table1 = PID(主键)+ 20 个其他列和来自 database1 的 200 条记录 AND table2 = [序列号](主键)+ 10 个其他列和来自 database2 的 300 条记录。

我正在尝试从 PID = [序列号] 的 table2 中提取值。

注意:PID = [SCK34ICV7, NSCK876DL, ......]。

我参考了“在 R 脚本中传递字符串变量以在 SQL 语句中使用它”

t1 <- sqlquery(db1, "select * from table1")
r1 <- t1$PID
class(r1) = 'factor'
t2 <- sqlquery(db2, "select * from table2 where [Serial no] = '(",r1,")' ",sep ="")

我还尝试了其他函数,即 gsubfn 和 sprintf() 中的 paste0()、fn$ 并得到错误,例如 -'c 不是可识别的内置函数名'; '语法错误'。

请提出最好的方法。

注册,

姆鲁通贾亚

【问题讨论】:

    标签: sql sql-server r printf rodbc


    【解决方案1】:

    您的查询已关闭。请参阅 here 了解正确的格式。

    r1 <- c("PID1","PID2","PID3")
    

    错误

    paste("select * from table2 where [Serial no] = '(",r1,")' ",sep ="")
    

    输出:

    [1] "select * from table2 where [Serial no] = '(PID1)' " "select * from table2 where [Serial no] = '(PID2)' " "select * from table2 where [Serial no] = '(PID3)' "
    

    正确

    paste("select * from table2 where [Serial no] IN (",paste(r1,collapse=", "),") ",sep ="")
    

    输出:

    [1] "select * from table2 where [Serial no] IN (PID1, PID2, PID3) "
    

    所以查询变成:

    t2 <- sqlquery(db2,paste0("select * from table2 where [Serial no] IN (",paste(r1,collapse=", "),") ",sep =""))
    

    希望这会有所帮助。

    【讨论】:

    • @ Florian,出现错误 - 42S22 207 [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]列名“PID1”无效。这是什么意思。
    • 您不应该将我的值用于 r1,我在示例中使用 r1 &lt;- c("PID1","PID2","PID3") 行创建了一些虚拟数据。您应该为此使用自己的声明。
    • 我使用了自己的向量 'r1'。 r1
    • 不。仅供参考,str(r1):带 300 个级别的因子“SCK34ICV7”,..:334 11465 21762 14917 20282 20927 15958 3514 7430 7207 ...
    • 嗯,你的代码中一定有“PID1”这个词吗?尝试 CTRL+F 并输入 PID1。
    猜你喜欢
    • 1970-01-01
    • 2014-02-16
    • 1970-01-01
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 2012-02-19
    • 2013-10-16
    • 2017-01-27
    相关资源
    最近更新 更多