tags:

views:

124

answers:

5

I've been using the sp_MSforeachtable built-in stored procedure to determine the row count of each table in our database, using COUNT(*).

I've realized, though, that I just want a 0 or 1, depending on whether there are any rows at all in the table.

Is there something else I can use that's faster/cheaper than COUNT(*)?

A: 

Maybe just grab the first row, and display a 1?

select top 1 1 from tablename

Dean J
Not sure why this was upvoted for TSQL?
p.campbell
@p.campbell: you could just ask for the correction, instead of spending your own rep on downvoting. :) Correction look right?
Dean J
@p.campbell; gave you an upvote anyways, hopefully that makes up for it.
Dean J
@Dean: actually I didn't downvote your answer! I agree with not wasting rep! But other definitely are downvoting my own!
p.campbell
+8  A: 

Consider this query. EXISTS will stop execution when it finds the first match.

IF EXISTS (SELECT 1 FROM MyTable)
BEGIN
   print 'at least one!'
END
ELSE
BEGIN
   print 'no rows found in table'
END
p.campbell
@Downvoter: explain why this doesn't solve the problem and/or help the OP?
p.campbell
A: 
SELECT TOP 1 ID FROM TABLE

Then you can do an EOF check when the recordset is returned.

Tom Gullen
A: 

sp_spaceused will probably be more efficient than COUNT(*).

Keep in mind that it does not update in real time so it may not be 100% accurate in all cases.

Dan Herbert
+3  A: 

This will print all the table names that have at least 1 row

exec sp_MSforeachtable 'if  exists (select 1 from ?) print ''?'''
SQLMenace