如何在不加入的情况下优化此存储过程

时间:2013-10-28 13:57:02

标签: sql sql-server stored-procedures query-optimization

对于即时搜索我有这种情况,但此查询有更多NOT IN检查

ALTER PROC [dbo].[DPR_SP_GetEmployeeDetailsByKeyword]
@keyword varchar(10),
@hotelId int
AS
BEGIN
SELECT  EmployeeDetails.EmployeeId,EmployeeDetails.SageEmployeeId,EmployeeDetails.FirstName,EmployeeDetails.LastName
FROM    EmployeeDetails
WHERE   (EmployeeDetails.EmployeeId NOT IN (    SELECT  EmployeeWorksIn.EmployeeId
                                                FROM    EmployeeWorksIn
                                                WHERE   EmployeeWorksIn.HotelId=@hotelId
                                                )
AND
        EmployeeDetails.EmployeeId LIKE @keyword+'%')
        OR
        (EmployeeDetails.EmployeeId NOT IN (    SELECT  EmployeeWorksIn.EmployeeId
                                                FROM    EmployeeWorksIn
                                                WHERE   EmployeeWorksIn.HotelId=@hotelId
                                                )
        AND
OR 
        (EmployeeDetails.EmployeeId NOT IN (    SELECT  EmployeeWorksIn.EmployeeId
                                                FROM    EmployeeWorksIn
                                                WHERE   EmployeeWorksIn.HotelId=@hotelId
                                                )
        AND
        EmployeeDetails.DateOfBirth LIKE @keyword+'%')

如何优化此查询

由于

1 个答案:

答案 0 :(得分:1)

您可以将其重写为

alter proc dbo.DPR_SP_GetEmployeeDetailsByKeyword 
    @keyword varchar(10),
    @hotelId int
As
Select
    e.EmployeeId,
    e.SageEmployeeId,
    e.FirstName,
    e.LastName
From
    EmployeeDetails e
        Left Outer Join
    EmployeeWorksIn w
        on e.EmployeeId = w.EmployeeId and w.HotelId = @hotelId
Where
    w.EmployeeID Is Null And (
        e.EmployeeId Like @keyword+'%' Or
        e.Something Like @keyword+'%' Or -- appears to be missing from question
        e.DateOfBirth Like @keyword+'%'
    );
之后,你会看到索引以加快速度。