[英]How to improve my query performance SQL Server
I have a temp table inside my procedure which joins with another temp table and it seems taking some time to run.我的程序中有一个临时表,它与另一个临时表连接,它似乎需要一些时间才能运行。 Could anyone suggest how to speedup this.
谁能建议如何加快速度。
Below is my piece of code:下面是我的一段代码:
declare @installs table
(
UserName varchar(200),
DeviceName varchar(500),
FirstSeenDate datetime
)
insert into @installs
SELECT [Username]
,[Device Name]
,min([First Seen]) as 'Install Date'
FROM [DataCollection].[dbo].[iBoss_Installed_Users]
where [Device Type] not like '%Server%'
group by [Device Name], Username
declare @installs_User table
(
UserName varchar(200),
InstalledDate varchar(max)
)
insert into @installs_User
select main.UserName,
left(main.installs,len(main.installs)-1) as "Installs"
From
(
select distinct ins2.UserName,
(
select convert(varchar(200),ins.FirstSeenDate)+', ' as [text()]
from @installs ins
where ins.UserName=ins2.UserName
order by ins.Username
for XML PATH('')
) [installs]
from @installs ins2
)[Main]
First these are not temp tables, these are table variables and SQL Server has hard coded statics for them, so estimation is always way off and they suck in that matter.首先,这些不是临时表,它们是表变量,SQL 服务器为它们提供了硬编码的静态数据,所以估计总是很遥远,而且它们在这件事上很糟糕。
So if you just use temp table instead and (maybe add index on them) will help a lot:因此,如果您只使用临时表并且(可能在它们上添加索引)将有很大帮助:
create table #installs
(
UserName varchar(200),
DeviceName varchar(500),
FirstSeenDate datetime
)
insert into #installs
SELECT [Username]
....
I would avoid using a table variable or temporary table, and instead use a common table expression.我会避免使用表变量或临时表,而是使用公用表表达式。 I'd also use
GROUP BY
rather than DISTINCT
, so the optimiser knows it doesn't have to try de-duplicating your list of dates...我也会使用
GROUP BY
而不是DISTINCT
,所以优化器知道它不必尝试对您的日期列表进行重复数据删除......
declare @installs_User table
(
UserName varchar(200),
InstalledDate varchar(max)
);
WITH
installs AS
(
SELECT [Username]
,[Device Name]
,min([First Seen]) as 'Install Date'
FROM [DataCollection].[dbo].[iBoss_Installed_Users]
where [Device Type] not like '%Server%'
group by [Device Name], Username
)
insert into
@installs_User
SELECT main.UserName
,left(main.installs,len(main.installs)-1) as "Installs"
From
(
SELECT
ins2.UserName,
(
select convert(varchar(200),ins.FirstSeenDate)+', ' as [text()]
from installs ins
where ins.UserName=ins2.UserName
order by ins.Username
for XML PATH('')
) [installs]
FROM
installs ins2
GROUP BY
ins2.UserName
)
[Main]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.