1

I am trying to construct a query where I check the number of rows returned from a sql select. For example, I want to check that if the number of rows returned from a query are greater than 3, then do something else do nothing

if @@rowcount(select clientId from Clients group by clientId) > 3
   PRINT 'WARNING'

Any ideas appreciated

3
  • Are you trying to do it all inside a query or are you using t-sql ? Commented Aug 19, 2011 at 16:45
  • Inside a query..want to set up a stored procedure Commented Aug 19, 2011 at 17:52
  • Well, in a Stored Procedure you can use T-SQL. As in select [at]count = count(*) from table where condition and then use the value of [at]count anywhere in your SP. If within a query, you have to do something like I said in my answer. You can put the case in the select or the where Commented Aug 19, 2011 at 18:22

3 Answers 3

4

Try:

case
    when (select count(*) from table where condition) > 3 Then
    else
end

Hope this helps...

Sign up to request clarification or add additional context in comments.

Comments

3
DECLARE @Count INT = (SELECT COUNT(DISTINCT ClientId) FROM Clients);

IF @Count > 3
    PRINT 'WARNING';

Comments

1

Hope this helps

[EDITED]

DECLARE @Cnt AS INT
select @Cnt = COUNT(clientId) from Clients group by clientId
if @Cnt > 3
PRINT 'WARNING'

2 Comments

This returns the data, whether there is 1 client or 100,000 clients. Not sure that is desired.
I changed from @@ROWCOUNT TO variable. Both my logic should work. This will show WARNING, if the client count is greater than 3 only.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.