简体   繁体   中英

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

I have a table in SQL server to which I am trying to add data. Before adding the data I want to delete all the existing records, but I do not want to delete the table and recreate it since it has index created in SQL server which I want to preserve.

What choices do I have to accomplish this using r?

There are multiple ways to delete all records in a table.

You can TRUNCATE or DELETE

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

EDIT: use dbExecute() instead of dbSendQuery() .

As commented in the documentation of 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.

However, send methods do not automatically clear the returned result object. Thereforeget and execute methods are more suitable for interactive use. From the dbSendStatement() doc:

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().

In case you need to delete ONLY certain records

To answer another use case when you need to delete only certain records from a database your could create a list of queries and then use map to execute them. For example, the next code would delete rows with id 1 through 5.

library(purrr) # for the map() function
library(comprehenr) # for the to_vec() function. This are list comprehensions in R.

# 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 = '", to_vec(for(id in ids) ids), "');")

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

Note that we use dbExecuteinstead of dbSendQuery because it returns the number of records affected so we can be certain that the operations happened.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM