A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
Hi @Hamed Vaziri ,
Welcome to Microsoft Q&A!
As mentioned by other experts, the most common problem for such behavior will be Parameters Sniffing problem.
When a stored procedure is first executed SQL Server looks at the input parameters and uses this as guidance to build the query plan. This is known as “parameter sniffing”.
This is good as long as the input parameters for the first invocation are typical for future invocations. But if that is not the case this will cause performance problems.
Your procedure may be like below:
CREATE PROCEDURE Myprocedure(@minDate char(10), @maxDate char(10))
AS
with cte1
as (
...
WHERE r.ReceptionDate BETWEEN @minDate AND @maxDate
...
)
select c.ZoneName as N' بخش'
, c.ServiceType as N'سرويس' ,c.InsType as N'بيمه' ,sum (c.SumQty) as N'تعداد', sum (c.SumTotalPrice) as N'جمع كل' ,sum(c.SumHesab) as N'جمع دريافتي'
from cte1 c
group by c.ZoneName, c.ServiceType,c.InsType
order by c.ZoneName
You could try below several solutions and check whether any of them is helpful to you.
One: Replace parameters with local variables.
CREATE PROCEDURE Myprocedure(@minDate char(10), @maxDate char(10))
AS
declare @local_minDate char(10), @local_maxDate char(10)
set @local_minDate = @minDate
set @local_maxDate = @maxDate;
with cte1
as (
...
WHERE r.ReceptionDate BETWEEN @local_minDate AND @local_maxDate
...
)
select c.ZoneName as N' بخش'
, c.ServiceType as N'سرويس' ,c.InsType as N'بيمه' ,sum (c.SumQty) as N'تعداد', sum (c.SumTotalPrice) as N'جمع كل' ,sum(c.SumHesab) as N'جمع دريافتي'
from cte1 c
group by c.ZoneName, c.ServiceType,c.InsType
order by c.ZoneName
Two: Execute using WITH RECOMPILE.
EXEC Myprocedure @minDate = '1399/11/01',@maxDate = '1399/11/30' WITH RECOMPILE;
Three: Query hint RECOMPILE
CREATE PROCEDURE Myprocedure(@minDate char(10), @maxDate char(10))
AS
with cte1
as (
...
WHERE r.ReceptionDate BETWEEN @minDate AND @maxDate
...
OPTION (RECOMPILE);
)
select c.ZoneName as N' بخش'
, c.ServiceType as N'سرويس' ,c.InsType as N'بيمه' ,sum (c.SumQty) as N'تعداد', sum (c.SumTotalPrice) as N'جمع كل' ,sum(c.SumHesab) as N'جمع دريافتي'
from cte1 c
group by c.ZoneName, c.ServiceType,c.InsType
order by c.ZoneName
You could also refer this article for more details and solutions.
Best regards
Melissa
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.