7

我想知道在某个 DELETE 操作中删除了多少行。

我采用了 Microsoft 示例 B,它是

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

并尝试对其进行修改以仅返回count已删除记录的:

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

但这会抛出

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

所以我尝试了

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

抛出

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

我错过了什么?

4

3 回答 3

10

只需运行您的查询并获取修改后的行

DELETE 
FROM datacache 
WHERE userId=@id

SELECT @@ROWCOUNT
于 2015-06-15T11:43:56.427 回答
9

您不能在OUTPUT子句中使用聚合。您可以将任何列输出到表变量中并从那里计数:

DECLARE @t TABLE(id int)

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

SELECT COUNT(*) FROM @t
于 2015-06-15T11:43:12.683 回答
1

之后如何计算记录?

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

SELECT COUNT(*)
FROM @DELETEDIDS;

或者,只需运行查询并使用@@ROWCOUNT.

于 2015-06-15T11:43:20.290 回答