如果我的大脑运作良好,我一直在努力解决一个似乎有简单解决方案的问题。我必须通过更改from_date和to_date的值,每月在SQL Server数据库中运行SQL存储过程。我无法弄清楚如何更改带引号的字符串中的值。这是我使用paste()的代码,它给了我错误。
to_date <- '20160229'
from_date <- '20160201'
require(RODBC)
dWA_ABCD_BT_D <- odbcDriverConnect('driver={SQL Server}; server=ABCD; database=dWA_ABCD_BT_D; trusted_connection=true')
sens.raw <- sqlQuery( dWA_ABCD_BT_D, "exec m_rawData_sens @from_dt = '20140301' , @to_dt = '20160229' " )
# Here the code using paste() that never worked-------------
sens.raw <- sqlQuery( dWA_ABCD_BT_D, paste("exec", "m_rawData_sens","@from_dt =", sQuote(from_date) , ",", "@to_dt =", sQuote(to_date) , sep=" " ))
# also tried without sQuote()
sens.raw <- sqlQuery( dWA_ABCD_BT_D, paste("exec", "m_rawData_sens","@from_dt =", from_date , ",", "@to_dt =", to_date , sep=" " ))
odbcClose(dWA_ABCD_BT_D)
这是我的错误消息
[1] "42000 102 [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near '‘'."
[2] "[RODBC] ERROR: Could not SQLExecDirect 'exec m_rawData_sens @from_dt = ‘20160201’ , @to_dt = ‘20160229’'"
我必须每月更改from_date和to_date,以便从R中执行16次SP执行。任何帮助都得到R社区的赞赏....谢谢
答案 0 :(得分:1)
从?sQuote()
使用ASCII 0x27
单引号,您可能必须将此行放在paste()
之前:
options( useFancyQuotes=FALSE)
另一种解决方法是将单引号直接放在字符串中,但使用paste0()
来避免引号和值之间的空格:
paste0("exec ", "m_rawData_sens ","@from_dt='", from_date , "', ", "@to_dt ='", to_date, "'" )