SQL Server Union性能改进

时间:2017-12-06 08:18:40

标签: sql sql-server

我有一张这样的表:

Table Data Stucture

此表有超过400k行。

我使用SQL Server函数获取值,如下所示;实际上我想获得最后的更新记录。

ALTER FUNCTION [dbo].[FncGetName] 
    (@Season VARCHAR(30),
     @NameCode VARCHAR(30))
RETURNS VARCHAR(150)
AS
BEGIN
    DECLARE @Name VARCHAR(150)

    SET @Name = (SELECT TOP 1 Names.Name 
                 FROM
                     (SELECT
                          CASE 
                             WHEN Name1Unidecode IS NOT NULL 
                                THEN Name1Unidecode 
                                ELSE Name1 
                          END AS Name       
                      FROM
                          Persons
                      WHERE
                          Season IS NOT NULL
                          AND Season = @Season
                          AND Name1Code LIKE @NameCode + '%'
                      GROUP BY  
                          Name1, Name1Unidecode

                      UNION

                      SELECT
                          CASE 
                             WHEN Name2Unidecode IS NOT NULL 
                                THEN Name2Unidecode 
                                ELSE Name2 
                          END AS Name
                      FROM
                          Persons 
                      WHERE
                          Season IS NOT NULL
                          AND Season = @Season
                          AND Name2Code LIKE @NameCode + '%'
                      GROUP BY 
                          Name2, Name2Unidecode) AS Names
             )

    RETURN @Name
END 

这是SELECT查询:

SELECT 
    ID, ISNULL(dbo.FncGetName(Season , NameCode),ShortName) AS Name 
FROM 
    Table1

那么有什么方法可以提高性能吗?

EDITED

我为UNION的SELECT查询创建了2个索引,如下所示,性能得到了提升。

CREATE NONCLUSTERED INDEX [Index_Name1] ON [dbo].[Person]
(
    [Season] DESC,
    [Name1Code] DESC,
    [Name1 DESC,
    [Name1Unidecode] DESC
)


CREATE NONCLUSTERED INDEX [Index_Name2] ON [dbo].[Person]
(
    [Season] DESC,
    [Name2Code] DESC,
    [Name2 DESC,
    [Name2Unidecode] DESC
)

1 个答案:

答案 0 :(得分:0)

我相信您应该使用以下查询而不是原始查询

    SELECT TOP 1
            coalesce(Name1Unidecode, Name1, Name2Unidecode, Name2) AS Name
    FROM Persons 
    WHERE Season IS NOT NULL
            AND Season = @Season
            AND (Name2Code LIKE @NameCode + '%' OR Name1Code LIKE @NameCode + '%')
   ORDER BY update desc

我假设属性NULLName1UnidecodeName1Name2Unidecode中只有一个值不是Name2。如果不是这样,请根据您的数据进行调整。

此外,如果您有索引Person(Season, Name2Code, update)Person(Season, Name1Code, update),那么它应该非常快。