Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Horrible sql server performance when capturing result in variable

I'm using SQL Server 2012.

When I run this query...

select 
    count(*)
from 
    MembershipStatusHistory msh
join 
    gym.Account a on msh.AccountID = a.AccountID
join 
    gym.MembershipType mt on a.MembershipTypeID = mt.MembershipTypeID
join 
    MemberTypeGroups mtg on mt.MemberTypeGroupID = mtg.MemberTypeGroupID
where 
    mtg.MemberTypeGroupID IN (1,2)
    and msh.NewMembershipStatus = 'Cancelled'
    and year(msh.ChangeDate) = year(getdate())
    and month(msh.ChangeDate) = month(getdate())
    and day(msh.ChangeDate) = day(getdate())

...it returns almost instantly. Great. Now, when I run the same exact query like this:

declare @CancellationsToday int

SET @CancellationsToday = (
    select  
        count(*)
    from MembershipStatusHistory msh
    join gym.Account a
    on msh.AccountID = a.AccountID
    join gym.MembershipType mt
    on a.MembershipTypeID = mt.MembershipTypeID
    join MemberTypeGroups mtg
    on mt.MemberTypeGroupID = mtg.MemberTypeGroupID
    where mtg.MemberTypeGroupID IN (1,2)
    and msh.NewMembershipStatus = 'Cancelled'
    and year(msh.ChangeDate) = year(getdate())
    and month(msh.ChangeDate) = month(getdate())
    and day(msh.ChangeDate) = day(getdate())
)

...it takes 1.5 MINUTES to return. Consistently, every time.

What the **** is going on? I have to use a variable because I need to sum the result later on in my stored proc. I am storing the results of other queries in the same proc and they are fast. I am stumped.

Here is the execution plan from the SLOW query: enter image description here

And here is the execution plan from the FAST query: enter image description here

I'll be honest, I don't know what these execution plans mean or what I need to correct.

like image 942
HerrimanCoder Avatar asked Dec 31 '25 16:12

HerrimanCoder


1 Answers

Very strange but try something like this....

declare @CancellationsToday int;

select @CancellationsToday = count(*)
from MembershipStatusHistory msh
join gym.Account a
on msh.AccountID = a.AccountID
join gym.MembershipType mt
on a.MembershipTypeID = mt.MembershipTypeID
join MemberTypeGroups mtg
on mt.MemberTypeGroupID = mtg.MemberTypeGroupID
where mtg.MemberTypeGroupID IN (1,2)
and msh.NewMembershipStatus = 'Cancelled'
and year(msh.ChangeDate) = year(getdate())
and month(msh.ChangeDate) = month(getdate())
and day(msh.ChangeDate) = day(getdate())
like image 99
M.Ali Avatar answered Jan 02 '26 10:01

M.Ali



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!