R- create temporary table in sql server from R data frame

主宰稳场 提交于 2019-12-04 06:49:35

Unfortunately, I don't recall sqlSave(conection, new_data, table_name, append = TRUE) ever working correctly for inserting data into existing tables (e.g. not creating new tables), so you may have to use the less efficient approach of generating the INSERT statements yourself. For example,

con <- odbcConnect(...)

query <- "
SET NOCOUNT ON;

IF ( OBJECT_ID('tempdb..##tmp_table') IS 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 INTO ##tmp_table ([Value]) VALUES ",
    paste0(sprintf("(%.2f)", df$Value), collapse = ", "),
    " SET NOCOUNT OFF; SELECT * FROM ##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) 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!