R- create temporary table in sql server from R data frame -
i know can create temporary table in sql r with, example:
require(rodbc) x<- odbcdriverconnect('driver={sql server}; server=s001000;database=x1;trusted_connection=true') sqlquery(x, "create table #temptable (test int)" ) sqlquery(x, "insert #temptable(test) values(201508)") doesitwork <- sqlquery(x, "select * #temptable")
but create temporary table in sql server r object (i have table has result of previous r calculations , need query against table in sql. don't want export txt , upload sql server. has way r. tried:
tabla<-data.frame(per=c(201508,201510)) sqlquery(x, "select * ##temporal tabla")
but got error message:
"42s02 208 [microsoft][odbc sql server driver][sql server]invalid object name 'tabla'." "[rodbc] error: not sqlexecdirect 'select * ##temporal tabla '"
i know can create table sqlsave:
sqlsave(x, tabla, rownames=false,safer=false)
but want create temporary table. how can create temporary table in sql r object?
unfortunately, don't recall sqlsave(conection, new_data, table_name, append = true)
ever working correctly inserting data existing tables (e.g. not creating new tables), may have use less efficient approach of generating insert
statements yourself. example,
con <- odbcconnect(...) query <- " set nocount on; if ( object_id('tempdb..##tmp_table') not null ) drop table ##tmp_table; create table ##tmp_table ( [id] int identity(1, 1) ,[value] decimal(9, 2) ); set nocount off; select 1; " sqlquery(con, gsub("\\s|\\t", " ", query)) df <- data.frame(value = round(rnorm(5), 2)) update_query <- paste0( "set nocount on; insert ##tmp_table ([value]) values ", paste0(sprintf("(%.2f)", df$value), collapse = ", "), " set nocount off; select * ##tmp_table;" ) sqlquery(con, update_query) # id value # 1 1 0.79 # 2 2 -2.23 # 3 3 0.13 # 4 4 0.07 # 5 5 0.50 #sqlquery(con, "drop table ##tmp_table;") #odbcclose(con)
Comments
Post a Comment