使用 R(DBI 包)从 SQL 服务器 table 中删除行

Delete rows from SQL Server table using R (DBI package)

我在 SQL 服务器中有一个 table,我正在尝试向其添加数据。在添加数据之前,我想删除所有现有记录,但我不想删除 table 并重新创建它,因为它在我想保留的 SQL 服务器中创建了索引。

我有什么选择可以使用 r 完成此操作?

有多种方法可以删除table中的所有记录。

您可以TRUNCATEDELETE

dbExecute(con, "TRUNCATE TABLE TableName")
dbExecute(con, "DELETE FROM TableName")

编辑:使用 dbExecute() 而不是 dbSendQuery()

dbSendQuery()

的文档中所述

This method is for SELECT queries only. Some backends may support data manipulation queries through this method for compatibility reasons. However, callers are strongly encouraged to use dbSendStatement() for data manipulation statements.

但是,send方法不会自动清除返回的结果对象。因此 get and execute methods are more suitable for interactive use. From the dbSendStatement() 文档:

To query the number of affected rows, call dbGetRowsAffected() on the returned result object. You must also call dbClearResult() after that. For interactive use, you should almost always prefer dbExecute().

如果您只需要删除某些记录

要回答另一个用例,当您只需要从数据库中删除某些记录时,您可以创建一个查询列表,然后使用 map 来执行它们。例如,下一个代码将删除 ID 为 1 到 5 的行。

library(purrr) # for the map() function

# listing the ids we want to delete
ids = c(1,2,3,4,5)

# creating list of DELETE queries with each id
delete_queries = paste0("DELETE FROM tablename WHERE (id = '", ids, "');")

# executing each query
map(.x = delete_queries, .f = dbExecute, conn = con)

请注意,我们使用 dbExecute 而不是 dbSendQuery,因为它 returns 受影响的记录数,因此我们可以确定操作已发生。