Pasting Values in SQL Query through R

前端 未结 2 1785
隐瞒了意图╮
隐瞒了意图╮ 2021-01-22 10:01

I have the following dataframe which contains the AxiomaID.

x<-c(0123, 234, 2348, 345, 3454)

And trying to run the following SQL Query withi

相关标签:
2条回答
  • 2021-01-22 10:27

    Try the following query:

    SQL6<-data.frame(sqlQuery(myConn, paste("SELECT top 10 [AxiomaDate] 
      ,[RiskModelID]
      ,[AxiomaID]
      ,[Factor1]
       FROM [PortfolioAnalytics].[Data_Axioma].[SecurityExposures]
       Where AxiomaID IN (", paste(x, collapse = ", "), ")")))
    

    Hope it helps!

    0 讨论(0)
  • 2021-01-22 10:46

    You would try a function like

    InsertListInQuery <- function(querySentence, InList) {
      InValues <- ""
    for (i in 1:length(InList)){
      if (i < length(InList)) {
        InValues <- paste(InValues,InList[[i]],",")}
      else {
        InValues <- paste(InValues,InList[[i]],sep = "")
      }
    
    }
      LocOpenParenthesis <- gregexpr('[(]', querySentence)[[1]][[1]]
      LocCloseParenthesis <- gregexpr('[)]', querySentence)[[1]][[1]]
      if (LocCloseParenthesis-LocOpenParenthesis==1) {
        querySentence<- gsub("[(]", paste("(",InValues,sep = ""), querySentence)
      }
     return (querySentence )
    }
    

    Function InsertListInQuery requires you to change your original query to one that use constraint IN () in WHERE clausule. What function does is to conform a string with vector elements separated by comma, and replace "(" string with the one composed. Finally, return a character variable. Hence, you can define your vector of constraints list of elements, your query and call the function as shown:

    x<-c(0123, 234, 2348, 345, 3454)
    query <- "SELECT top 10 [AxiomaDate] 
      ,[RiskModelID]
    ,[AxiomaID]
    ,[Factor1]
    FROM [PortfolioAnalytics].[Data_Axioma].[SecurityExposures]
    Where AxiomaID IN ()"
    finalQuery <- InsertListInQuery(query, x)
    

    Value of finalQuery is:

    finalQuery
    [1] "SELECT top 10 [AxiomaDate] \n  ,[RiskModelID]\n,[AxiomaID]\n,[Factor1]\nFROM [PortfolioAnalytics].[Data_Axioma].[SecurityExposures]\nWhere AxiomaID IN ( 123 , 234 , 2348 , 345 ,3454)"
    

    Note the line return with special character \n.

    I hope it may help.

    0 讨论(0)
提交回复
热议问题