I have a proc that inserts records to a temp table. In pseudocode it looks like this:
Create temp table
a. Insert rows into temp table based on stringent criteria
b. if no rows were inserted, insert based on less stringent criteria
c. if there are still no rows, try again with even less stringent criteria
select from temp table
There are a lot of IF @@rowcount = 0 checks in the code to see if the table has any rows. The issue is that the proc isn’t really doing what it looks like it should be doing and it’s inserting the same row twice (steps a and c are being executed). However, if I change it to check this way IF ( (select count(*) from @temp) = 0) the proc works exactly as expected.
Which makes me think that @@rowcount isn’t the best solution to this problem. But I’m adding in extra work via the SELECT COUNT(*). Which is the better solution?
@@rowcount is the better solution. The work is already done. Selecting count(*) causes the database to do more work.
You need to make sure you are not doing something that will affect the value of @@rowcount before checking the value of @@rowcount. It is usually best to check @@rowcount immediately after performing the insert statement. If necessary assign the value to a variable so you can check it later:
Storing the row count immediately after any operation that changes row count will allow you to use the value more than once.