Wednesday, March 7, 2012

Fast Query

Hi,
What the best and fast way to check if a table has rows?
ThanksTry,
if exists(select * from dbo.t1)
print 'has rows.'
else
print 'no row'
AMB
"Chris" wrote:
> Hi,
> What the best and fast way to check if a table has rows?
> Thanks|||id have to disagree
if exists(select top 1 field1 from dbo.t1)
> print 'has rows.'
> else
> print 'no row'
"Alejandro Mesa" wrote:
> Try,
> if exists(select * from dbo.t1)
> print 'has rows.'
> else
> print 'no row'
>
> AMB
> "Chris" wrote:
> > Hi,
> > What the best and fast way to check if a table has rows?
> >
> > Thanks|||The difference between Alejandro and Michael's solutions is extremely small.
Alejandro provides the standard solution. It's efficient, easy to read, and
transportable. Michaels solution may in some limited situations be ever so
slightly more efficient but we are taking about a single page read.
Chris,
Go with Alejandro's solution... You'll be glad you did.
"Michael Evanchik" <MichaelEvanchik@.discussions.microsoft.com> wrote in
message news:65610958-F782-4F2B-B07B-EB80E65C7C80@.microsoft.com...
> id have to disagree
> if exists(select top 1 field1 from dbo.t1)
>> print 'has rows.'
>> else
>> print 'no row'
>
> "Alejandro Mesa" wrote:
>> Try,
>> if exists(select * from dbo.t1)
>> print 'has rows.'
>> else
>> print 'no row'
>>
>> AMB
>> "Chris" wrote:
>> > Hi,
>> > What the best and fast way to check if a table has rows?
>> >
>> > Thanks|||Actually I think that way has more of a potential to do more work. When you
use IF EXISTS with a SELECT * you give sql server the choice of what column
or index to use to determine if the row exists. If you specify a column
name it has to use that column. There is no need to use TOP 1 since EXISTS
will always stop after the first match is found.
--
Andrew J. Kelly SQL MVP
"Michael Evanchik" <MichaelEvanchik@.discussions.microsoft.com> wrote in
message news:65610958-F782-4F2B-B07B-EB80E65C7C80@.microsoft.com...
> id have to disagree
> if exists(select top 1 field1 from dbo.t1)
>> print 'has rows.'
>> else
>> print 'no row'
>
> "Alejandro Mesa" wrote:
>> Try,
>> if exists(select * from dbo.t1)
>> print 'has rows.'
>> else
>> print 'no row'
>>
>> AMB
>> "Chris" wrote:
>> > Hi,
>> > What the best and fast way to check if a table has rows?
>> >
>> > Thanks|||Thanks guys!
"Chris" wrote:
> Hi,
> What the best and fast way to check if a table has rows?
> Thanks

No comments:

Post a Comment