且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将R数据帧插入SQL Server中的现有表

更新时间:2023-01-29 08:37:21

我使用R和PostGreSQL以及r-postgres特定的驱动程序也有类似的需求.我认为SQLServer可能存在类似的问题.我发现***的解决方案是使用dbWriteTable或基础函数之一写入数据库中的临时表,以从流中写入以加载非常大的表(例如,对于Postgres,postgresqlCopyInDataframe).后者通常需要在定义和对齐SQL数据类型和R类类型方面进行更多工作,以确保编写,而dbWriteTable往往更容易一些.一旦写入临时表,就可以发出一条SQL语句,就像在数据库环境中一样,将其插入到表中.下面是使用高级DBI库数据库调用的示例:

I've had similar needs using R and PostGreSQL using the r-postgres-specific drivers. I imagine similar issues may exist with SQLServer. The best solution I found was to write to a temporary table in the database using either dbWriteTable or one of the underlying functions to write from a stream to load very large tables (for Postgres, postgresqlCopyInDataframe, for example). The latter usually requires more work in terms of defining and aligning SQL data types and R class types to ensure writing, wheres dbWriteTable tends to be a bit easier. Once written to a temporary table, to then issue an SQL statement to insert into your table as you would within the database environment. Below is an example using high-level DBI library database calls:

  dbExecute(conn,"start transaction;")
  dbExecute(conn,"drop table if exists myTempTable")
  dbWriteTable(conn,"myTempTable",df)
  dbExecute(conn,"insert into myRealTable(a,b,c) select a,b,c from myTempTable")
  dbExecute(conn,"drop table if exists myTempTable")
  dbExecute(conn,"commit;")