Jump to content
Xtreme .Net Talk

Recommended Posts

Posted
If I sum a field then the @@rowcount will always equal at least 1 or at least it appears that way. So if i only want to execute certain statements if the rowcount is "truly" equal to at least 1 then what do I do?
  • *Experts*
Posted

If you mean the SUM returns more than one, then you need to set a variable and use that. If the SUM returns any number, then @@rowcount will be 1. It might be more than one, if you have a GROUP BY. Remember that @@rowcount is the number of rows returned - in a typical SELECT SUM(...) you're returning one row, one column (the sum) - so @@rowcount will be 1. If the WHERE clause returned no records and the SELECT SUM(...) return NULL, then @@rowcount would be 0.

 

What you probably want is:

DECLARE @count int
SELECT @count = SUM(...) FROM table1 WHERE...

IF @count > 0
BEGIN
   -- Do something here
END

 

-nerseus

"I want to stand as close to the edge as I can without going over. Out on the edge you see all the kinds of things you can't see from the center." - Kurt Vonnegut
Posted

it is returning a null but the @@rowcount returns 1.

 

       use northwind

      declare @thisrows int

      select sum(unitprice) from [order details] where orderid=999999

      set @thisrows=@@rowcount

      print cast(@thisrows as nvarchar)

 

I handled it with something similar to what you suggested but is not null instead of zero because this is for a billing project and even if it zero the project will still need to issue an invoice

  • *Experts*
Posted

You probably should wrap the query with IsNull or COALESCE to convert the sum. Something like:

select IsNull(sum(unitprice), 0) from [order details] where orderid=999999

 

You usually only use @@rowcount when performing an UPDATE, INSERT or DELETE to check how many rows were affected. On a SELECT, the @@rowcount is useful, but not so much when doing a SUM or other aggregate function.

 

-ner

"I want to stand as close to the edge as I can without going over. Out on the edge you see all the kinds of things you can't see from the center." - Kurt Vonnegut

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...