Pasting Values in SQL Query through R

为君一笑 提交于 2019-12-02 03:36:49

问题


I have the following dataframe which contains the AxiomaID.

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

And trying to run the following SQL Query within R.

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

How can I paste all the x values which contain the AxiomaID's into the SQL Query?


回答1:


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!




回答2:


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.



来源:https://stackoverflow.com/questions/46390328/pasting-values-in-sql-query-through-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!