SQL Server提高了查询性能#Temp Table,Bulk insert

时间:2016-06-24 13:17:44

标签: sql sql-server performance stored-procedures sql-server-2008-r2

我正在研究一个旧的审计存储过程,该过程需要很长时间才能获得导致系统超时的数据。我们设法将时间从20多分钟缩短到运行一分钟,这仍然太长了。

我在SQL Server 2008 R2上运行。

我的问题是我有什么办法可以提高查询速度吗?特别是临时表和批量插入语句。

SELECT 
    dbo.[Audit Result Entry Detail].PK_ID,
    + every other value in the table (all values required)
INTO
    #temp5
FROM 
    dbo.[Audit Result Entry Detail]

INNER JOIN然后dbo.[Audit Register]发生另一个选择,并添加到另一个临时表#result

结果临时表获取旧的和新的结果值以进行比较。下面我提供了#temp5上发生的事件。请注意,这些只是片段;存储过程太大而无法发布所有内容。

SELECT 
    RED.[FK_RegisterID],
    total of a 106 rows are selected here :( 
FROM
    #temp5 AS RED
LEFT JOIN 
    #temp5 AS OLD ON RED.IdentityColumn = OLD.IdentityColumn
LEFT JOIN
    [Audit Register] AS REG ON REG.PK_ID = RED.FK_RegisterID

SELECT MAX(PK_ID) 
OVER (PARTITION BY FK_RegisterID) AS MAX_PK_ID
FROM #temp5

DROP TABLE #temp5

我的问题的第二部分是在存储过程最顶层创建的表中的批量插入

DECLARE @AuditOverView TABLE 
(
   FK_RegisterID INT,
   Audit_Date DATETIME,
   ContextUser NVARCHAR(30),
   Original_Value NVARCHAR(255),
   New_Value NVARCHAR(255),
   Assay NVARCHAR(200),
   Inst NVARCHAR(40),
   LotLevel NVARCHAR(3),
   Lot_ExpiryDate NVARCHAR(10),
   Lot_Number NCHAR(50),
   Audit_Type NVARCHAR(10),
   Partnumber INT,
   [Type] NVARCHAR(50),
   SubType NVARCHAR(50)
 )

下面的插入声明:

INSERT INTO @AuditOverView 
    SELECT DISTINCT 
        t.FK_RegisterID,
        t.Audit_Date,
        t.ContextUser,
        CONVERT(NVARCHAR, Original_Date_Run, 127) AS Original_Value,
        CONVERT(NVARCHAR, New_Date_Run, 127) AS New_Value,
        t.Assay AS 'Assay',
        Instrument AS 'Inst',
        '1' AS 'LotLevel',
        Lot1_Expiry_Date AS 'Lot_ExpiryDate',
        Lot1Number AS 'Lot_Number',
        t.Audit_Type,
        part_number AS Partnumber,
        'QC Result' AS [Type],
        'Result Date' AS SubType
    FROM
        #Result AS t
    INNER JOIN 
        (SELECT MAX(Audit_Date) AS DATE, FK_RegisterID
         FROM #Result
         GROUP BY FK_RegisterID) dt ON t.FK_RegisterID = dt.FK_RegisterID
                                    AND t.Audit_Date = dt.DATE
    WHERE 
        RTRIM(Lot1Number) != ''
        AND (CONVERT(NVARCHAR, Original_Date_Run, 120) != CONVERT(NVARCHAR, New_Date_Run, 120)
            OR t.Audit_Type = 'i'
            OR t.Audit_Type = 'd')

此插入语句大约发生50次,并且唯一的行更改是:

'Result Date' AS SubType
CONVERT(NVARCHAR, Original_Date_Run, 120) != CONVERT(NVARCHAR, New_Date_Run, 120)

如果需要,我可以提供更多信息。任何帮助将非常感谢提高性能。

0 个答案:

没有答案