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?
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.
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.
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.
Just run your query and get the modified rows
DELETE
FROM datacache
WHERE userId=@id
SELECT @@ROWCOUNT
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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With