Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting always 0 rows when using @@ROWCOUNT before IF EXISTS statement

Tags:

sql

sql-server

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.

like image 259
Misha Zaslavsky Avatar asked Dec 12 '25 17:12

Misha Zaslavsky


2 Answers

  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

like image 67
Nithesh Narayanan Avatar answered Dec 15 '25 08:12

Nithesh Narayanan


@@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.

like image 22
knkarthick24 Avatar answered Dec 15 '25 10:12

knkarthick24



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!