DELETE 后计算删除的记录

Count deleted records after a DELETE

我尝试计算在 DELETE 命令后将删除多少条记录:

SELECT COUNT(*) FROM BOXES
WHERE EXISTS  ( 
    DELETE FROM BOXES WHERE product='25043620' AND Order='0846'
)

我在删除附近遇到语法错误,但我不知道是哪一个。

我认为您不能将计数和删除结合起来。单独做。

这是一个例子:-

Example - Using SQL EXISTS Clause

You can also perform more complicated deletes.

You may wish to delete records in one table based on values in another table. Since you can't list more than one table in the SQL FROM clause when you are performing a delete, you can use the SQL EXISTS clause.

For example:

DELETE FROM suppliers
WHERE EXISTS
  ( SELECT customers.customer_name
    FROM customers
    WHERE customers.customer_id = suppliers.supplier_id
    AND customers.customer_name = 'IBM' );

This SQL DELETE example would delete all records in the suppliers table where there is a record in the customers table whose name is IBM, and the customer_id is the same as the supplier_id.

If you wish to determine the number of rows that will be deleted, you can run the following SQL SELECT statement before performing the delete.

SELECT COUNT(*) FROM suppliers
WHERE EXISTS
  ( SELECT customers.customer_name
    FROM customers
    WHERE customers.customer_id = suppliers.supplier_id
    AND customers.customer_name = 'IBM' );

这来自SQL: DELETE Statement

您可以尝试将语句放入一个循环中,并将参数作为循环条件,然后让循环在递增时为您计数。

经过一番挖掘,我想通了......

DELETE FROM BOXES WHERE product='25043620' AND Order='0846'

我要求数据库进行更改:

SELECT changes()

我知道删除了多少行。

对于那些为了 SQLServer 而来到这里的人 - 你会使用:

SET NOCOUNT OFF
DELETE FROM BOXES WHERE product='25043620' AND Order='0846'
SELECT @@ROWCOUNT

我不确定这在 SqlLite 中是否有效,但是,如果有人可以确认,那就太好了:)

我也有这个问题,不过我用的是C库。有一个函数可以为您提供:https://www.sqlite.org/c3ref/changes.html.

我这样做了...

    // using String = std::string;
    // execute: runs the query
    uint32_t Db::executeWithCount(const String& query) {
        uint32_t count = 0;
        if(execute(query, detail::empty_callback, nullptr)) {
            // number of rows affected by most recent INSERT, UPDATE or DELETE
            count = sqlite3_changes(_db);
        }

        return count;
    }