Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DELETE ... OUTPUT COUNT(DELETED.*)

I want to know how many rows were removed in a certain DELETE operation.

I took the Microsoft example B which is

DELETE Sales.ShoppingCartItem
OUTPUT DELETED.* 
WHERE ShoppingCartID = 20621;

and tried to modify it to return only the count of deleted records:

DELETE FROM datacache 
OUTPUT COUNT(DELETED.*)
WHERE userId=@id

but this throws

ExceptionMessage: "Incorrect syntax near '*'."
ExceptionType: "System.Data.SqlClient.SqlException"
Message: "Error"

So I tried

DELETE FROM datacache 
OUTPUT COUNT(DELETED)
WHERE userId=@id

which throws

ExceptionMessage: "Invalid column name 'DELETED'."
ExceptionType: "System.Data.SqlClient.SqlException"
Message: "Error"

What did I miss?

like image 795
Alexander Avatar asked Jun 15 '15 11:06

Alexander


People also ask

How do I count a deleted record in SQL?

Step 1: Use the beneath referenced command to check the number of rows present in the table from which the data got erased. Step 3: Collect all the data about the erased records from the SQL Server table to recover data. By using this command, you will acquire a Transaction ID of deleted records.

How do I count a deleted record in Oracle?

SQL> create table dt_del_ex(id number); Table created. SQL> set serveroutput on SQL> BEGIN 2 3 INSERT INTO dt_del_ex VALUES(1); 4 5 DBMS_OUTPUT. put_line(TO_CHAR(SQL%ROWCOUNT)||' rows inserted'); 6 7 INSERT INTO dt_del_ex select rownum from dual connect by level <=10; 8 9 DBMS_OUTPUT.

How do you delete multiple values in SQL?

To remove one or more rows in a table: First, you specify the table name where you want to remove data in the DELETE FROM clause. Second, you put a condition in the WHERE clause to specify which rows to remove. If you omit the WHERE clause, the statement will remove all rows in the table.


3 Answers

Just run your query and get the modified rows

DELETE 
FROM datacache 
WHERE userId=@id

SELECT @@ROWCOUNT
like image 138
Simone Avatar answered Oct 12 '22 23:10

Simone


You can not use aggregates in OUTPUT clause. You can output any column into table variable instead and count from there:

DECLARE @t TABLE(id int)

DELETE FROM Sales.ShoppingCartItem
OUTPUT Deleted.ShoppingCartID INTO @t
WHERE ShoppingCartID = 20621;

SELECT COUNT(*) FROM @t
like image 27
Giorgi Nakeuri Avatar answered Oct 12 '22 23:10

Giorgi Nakeuri


How about counting the records afterwards?

DELETE Sales.ShoppingCartItem
OUTPUT DELETED.ID INTO @DELETEDIDS
WHERE ShoppingCartID = 20621;

SELECT COUNT(*)
FROM @DELETEDIDS;

Or, just run the query and use @@ROWCOUNT.

like image 42
Gordon Linoff Avatar answered Oct 12 '22 23:10

Gordon Linoff