简体   繁体   中英

SQL query variable

i have a sql query which grabs trade data for a specific stock. i am trying to now loop through different stocks to apply a specific analysis. the code below shows my attempt at passing a variable to the query in the loop, as well as the "hardcoded" query.

any guidance will be greatly appreciated.

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

Thanks sgibb,

?paste solves the issue:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM