Counting the number of deleted rows in a SQL Server stored procedure

前端 未结 7 1709
借酒劲吻你
借酒劲吻你 2021-02-06 20:26

In SQL Server 2005, is there a way of deleting rows and being told how many were actually deleted?

I could do a select count(*) with the s

相关标签:
7条回答
  • 2021-02-06 21:08

    Out of curiosity, how are you calling the procedure? (I'm assuming it is a stored procedure?). The reason I ask is that there is a difference between a stored procedure's return value (which would be 0 in this case), and a rowset result -- which in this case would be a single row with a single column. In ADO.Net, the former would be accessed by a parameter and the latter with a SqlDataReader. Are you, perhaps, mistaking the procedure's return value as the rowcount?

    0 讨论(0)
  • 2021-02-06 21:11

    Create temp table with one column, id.

    Insert into temp table selecting the ids you want to delete. That gives you your count.

    Delete from your table where id in (select id from temp table)

    0 讨论(0)
  • 2021-02-06 21:12

    I use @@ROWCOUNT for this exact purpose in SQL2000 with no issues. Make sure that you're not inadvertantly resetting this count before checking it though (BOL: 'This variable is set to 0 by any statement that does not return rows, such as an IF statement').

    0 讨论(0)
  • 2021-02-06 21:19

    In your example @@ROWCOUNT should work - it's a proper way to find out a number of deleted rows. If you're trying to delete something from your application then you'll need to use SET NOCOUNT ON

    According to MSDN @@ROWCOUNT function is updated even when SET NOCOUNT is ON as SET NOCOUNT only affects the message you get after the the execution.

    So if you're trying to work with the results of @@ROWCOUNT from, for example, ADO.NET then SET NOCOUNT ON should definitely help.

    0 讨论(0)
  • 2021-02-06 21:21

    I found a case where you can't use @@rowcount, like when you want to know the distinct count of the values that were deleted instead of the total count. In this case you would have to do the following:

    delete from mytable 
    where datefield = '5-Oct-2008' 
    output deleted.datefield into #doomed
    
    select count(distinct datefield)
    from #doomed
    

    The syntax error in the OP was because output did not include deleted before the datefield field name.

    0 讨论(0)
  • 2021-02-06 21:28

    Have you tried SET NOCOUNT OFF?

    0 讨论(0)
提交回复
热议问题