我已经创建了一个存储过程来获取数据。在这个存储过程中,我返回了1个表,表存储了10万+数据以上的数据。所以现在我已经运行了存储过程,那时我在1分钟的时间内获取数据。我只想在1秒内获取数据。我也设置SET NOCOUNT ON;
并创建缺失索引。我仍然得到获取数据的相同时间。
这是我的疑问:
DECLARE @CurMon int
DECLARE @year nvarchar(max)
SELECT @CurMon = month(getdate())
SELECT @year = year(getdate())
SELECT
FORMAT(dateadd(MM, T.i, getdate()),'MMM-yy') AS DateColumn,
ISNULL(uf.TotalCount, 0) as TotalCount
FROM
(VALUES (12-@CurMon),(11-@CurMon),(10-@CurMon),(9-@CurMon),(8-@CurMon),(7-@CurMon),(6-@CurMon), (5-@CurMon), (4-@CurMon), (3-@CurMon), (2-@CurMon), (1-@CurMon)) AS T(i)
OUTER APPLY
(SELECT DISTINCT
COUNT(datepart(MM,UF.InsertDateTime)) OVER (partition by datepart(MM,UF.InsertDateTime)) AS TotalCount
FROM dbo.UserFollowers UF
INNER JOIN dbo.Users U on U.UserId = UF.FollowerId
WHERE DATEDIFF(mm,UF.InsertDateTime, DATEADD(mm, T.i, GETDATE())) = 0 and UF.IsFollowed = 1
) uf
order by DATEPART(MM,convert(datetime,FORMAT(dateadd(MM, T.i, getdate()),'MMMM') +'01 '+@year,110))
我也尝试了一些其他查询来提高查询速度,但我仍然得到相同的时间。这里这个查询也打印出来。
declare @StartDate datetime = dateadd(year , datediff(year , 0, getdate() ) , 0)
declare @tempT2 table
(
MNo int,
[Month] datetime,
NextMonth datetime)
;with Months as (
select top (12)
MNo = row_number() over (order by number)
,[Month] = dateadd(month, row_number() over (order by number) -1, @StartDate)
, NextMonth = dateadd(month, row_number() over (order by number), @StartDate)
from master.dbo.spt_values
)
insert into @tempT2
select * from Months
select
m.MNo
, Month = format(m.Month, 'MMM-yy')
, tally = count(UF.InsertDateTime)
from @tempT2 m
left join dbo.UserFollowers UF
INNER JOIN dbo.Users U on U.UserId = UF.FollowerId
on UF.InsertDateTime >= m.Month
and UF.InsertDateTime < m.NextMonth where UF.IsFollowed = 1
group by m.MNo,format(m.Month, 'MMM-yy')
order by MNo
这是我的两个查询我已经尝试但仍然没有成功提高查询的速度。抱歉,但我在这里看不到我的查询执行计划实际上我没有获得许可。
答案 0 :(得分:1)
通过切换到临时表而不是表变量,并通过删除format()
,您可以获得一点性能:
declare @StartDate datetime = dateadd(year , datediff(year , 0, getdate() ) , 0)
create table #Months (
MNo int not null primary key
, Month char(6) not null
, MonthStart datetime not null
, NextMonth datetime not null
)
;with Months as (
select top (12)
MNo = row_number() over (order by number)
, MonthStart = dateadd(month, row_number() over (order by number) -1, @StartDate)
, NextMonth = dateadd(month, row_number() over (order by number), @StartDate)
from master.dbo.spt_values
)
insert into #Months (MNo, Month, MonthStart, NextMonth)
select
MNo
, Month = stuff(convert(varchar(9),MonthStart,6),1,3,'')
, MonthStart
, NextMonth
from Months;
select
m.MNo
, m.Month
, tally = count(UF.InsertDateTime)
from @tempT2 m
inner join dbo.Users U
on UF.InsertDateTime >= m.MonthStart
and UF.InsertDateTime < m.NextMonth
inner join dbo.UserFollowers UF
on U.UserId = UF.FollowerId
and UF.IsFollowed = 1
group by
m.MNo
, m.Month
order by MNo
之后,您应该评估执行计划,以确定是否需要更好的索引策略。
如果您仍然需要它更快,您可以创建一个实际的日历表并查看创建索引视图。索引视图可以是一件苦差事,让它根据你的sql server版本正确运行,但会更快。
参考:
format
performance - Aaron Bertrand