SQL查询变量

时间:2012-11-22 09:08:51

标签: sql r

我有一个SQL查询,可以获取特定股票的交易数据。我正试图循环通过不同的股票来应用具体的分析。下面的代码显示了我尝试将变量传递给循环中的查询,以及“硬编码”查询。

任何指导都将不胜感激。

my.stocks <- c('ABL','IPL')

for (i in 1:2)
{
channel <- odbcConnect("Public_Trades")
my.frame1 <- sqlQuery(channel,
"SELECT TRADE_DATE_TIME,
 PRICE,
 QUANTITY
 FROM [ISLDWODS].[HERMES_PUBLIC].[PUBLIC_TRADES_HISTORY]
 where TRADE_DATE_TIME > '2012-11-01' and TRADE_TYPE ='AT' and INSTR_CODE = " & my.stocks[i] &  
 "order by TRADE_DATE_TIME asc")

my.frame2 <- sqlQuery(channel,
"SELECT TRADE_DATE_TIME,
 PRICE,
 QUANTITY
 FROM [ISLDWODS].[HERMES_PUBLIC].[PUBLIC_TRADES_HISTORY]
 where TRADE_DATE_TIME > '2012-11-01' and TRADE_TYPE in ('AT','UT') and INSTR_CODE = 'MPC'  
 order by TRADE_DATE_TIME asc")


close(channel)
}

1 个答案:

答案 0 :(得分:0)

谢谢sgibb,

?paste解决了这个问题:

my.stocks <- c("'ABL'","'IPL'")


for (i in 1:2)
{

my.string1 <- paste("SELECT TRADE_DATE_TIME,PRICE,QUANTITY  
              FROM [ISLDWODS].[HERMES_PUBLIC].[PUBLIC_TRADES_HISTORY] 
              where TRADE_DATE_TIME > '2012-11-01' and TRADE_TYPE ='AT' and INSTR_CODE = ", my.stocks[1]," order by TRADE_DATE_TIME asc")

my.string2 <- paste("SELECT TRADE_DATE_TIME,PRICE,QUANTITY  
              FROM [ISLDWODS].[HERMES_PUBLIC].[PUBLIC_TRADES_HISTORY] 
              where TRADE_DATE_TIME > '2012-11-01' and TRADE_TYPE in ('AT','UT') and INSTR_CODE = ", my.stocks[1]," order by TRADE_DATE_TIME asc")

channel <- odbcConnect("Public_Trades")
my.frame1 <- sqlQuery(channel,my.string1)

my.frame2 <- sqlQuery(channel,my.string2)
}