I am getting always 0 when using @@ROWCOUNT after IF EXISTS, why?
Here is my code:
IF EXISTS (SELECT TOP 1 1 FROM MyTable) --Returns one row.
SELECT @@ROWCOUNT; --Returns always 0
I know that the statement doesn't logical right now, because I expect it to print always 1, so I can also SELECT 1, but it is just for demonstration of the problem. The problem it doesn't print 1, it always prints 0.
SELECT TOP 1 1 FROM Provider.Site
SELECT @@ROWCOUNT; --Returns 1
IF EXISTS (SELECT TOP 1 1 FROM Provider.Site) --Returns one row.
SELECT @@ROWCOUNT; --Returns always 0
Here first @@ROWCOUNT return 1 and second returns 0.
Since EXISTS returns only true or false and there is no rows affected since it doesn't select any records. It checks the existence only.
Since @@ROWCOUNT returns the number of rows affected by the last statement second case that willl be 0
@@ROWCOUNT by default has 0.
SELECT @@ROWCOUNT; --Returns always 0
SELECT within IF LOOP will change the @@ROWCOUNT to 1.
But after that IF EXISTS condition will change the @@ROWCOUNT to 0 again, and that is the reason you are getting 0 always. Scope of SELECT wont exist anymore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With