如何提高我的查询性能 SQL 服务器

How to improve my query performance SQL Server

我的程序中有一个临时文件 table,它与另一个临时文件 table 相连,似乎需要一些时间才能 运行。 谁能建议如何加快速度。

下面是我的一段代码:

    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]
        

首先这些不是临时 tables,这些是 table 变量并且 SQL 服务器对它们有硬编码的静态信息,所以估计总是有偏差并且他们吸收了那个事.

因此,如果您只使用临时 table 并且(可能在其上添加索引)将会有很大帮助:

create table #installs
    (
        UserName varchar(200),
        DeviceName varchar(500),
        FirstSeenDate datetime
    )

insert into #installs
SELECT  [Username] 
....

我会避免使用 table 变量或临时 table,而是使用常见的 table 表达式。我还会使用 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]