DELETE ... OUTPUT COUNT(DELETED。*)

时间:2015-06-15 11:37:32

标签: sql sql-server output-clause

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

我拿了the Microsoft example 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"

我错过了什么?

3 个答案:

答案 0 :(得分:7)

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

DELETE 
FROM datacache 
WHERE userId=@id

SELECT @@ROWCOUNT

答案 1 :(得分:5)

您不能在DECLARE @t TABLE(id int) DELETE FROM Sales.ShoppingCartItem OUTPUT Deleted.ShoppingCartID INTO @t WHERE ShoppingCartID = 20621; SELECT COUNT(*) FROM @t 子句中使用聚合。您可以将任何列输出到表变量中,并从那里开始计数:

path("mypath") {

  post {
    decodeRequest {
      entity(as[String]) {jsonStr => //could not find implicit value for...FromRequestUnmarshaller[String]
        complete {
          val json: JsObject = Json.parse(jsonStr).as[JsObject]
          val jsObjectFuture: Future[JsObject] = MyDatabase.addListItem(json)
          jsObjectFuture.map(_.as[String])
        }
      }          
    }
  }
}

答案 2 :(得分:1)

如何计算之后的记录?

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

SELECT COUNT(*)
FROM @DELETEDIDS;

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