简体   繁体   English

DELETE ... OUTPUT COUNT(DELETED。*)

[英]DELETE … OUTPUT COUNT(DELETED.*)

I want to know how many rows were removed in a certain DELETE operation. 我想知道在某个DELETE操作中删除了多少行。

I took the Microsoft example B which is 我拿了微软的例子B

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

and tried to modify it to return only the count of deleted records: 并尝试修改它以仅返回已删除记录的count

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? 我错过了什么?

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. 您不能在OUTPUT子句中使用聚合。 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 . 或者,只需运行查询并使用@@ROWCOUNT

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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