在R语句中使用R子句的where子句在SQL语句中使用它

时间:2017-08-07 10:27:00

标签: sql sql-server r printf rodbc

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

我试图从table2中提取值,其中PID = [Serial no]。

注意: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 ="")

我还尝试了其他函数viz paste0(),fn $来自gsubfn和sprintf()并得到错误 - &#39; c不是公认的内置函数名称&#39; ; &#39;语法错误&#39;。

请建议最好的方法。

注册,

Mrutyunjaya

1 个答案:

答案 0 :(得分:3)

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

rowhtml.children[0].innerText

<强>错

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) "

希望这有帮助。