替换SQL查询

时间:2011-07-22 06:00:05

标签: sql sql-server sql-server-2008 case-when

我想替换此查询

DECLARE @tmpUser TABLE( UserId INT, UserType INT )

INSERT INTO @tmpUser
SELECT
    u.UserId,
    1
FROM
    Users u (nolock)
WHERE
    u.UPIN = @AttendingDoctorID

IF @@ROWCOUNT = 0
BEGIN
    INSERT INTO @tmpUser
    SELECT
        u.UserId,
        1
    FROM
        Users u (nolock)
    WHERE
        u.FirstName = @AttendingDoctorFirstName AND
        u.LastName = @AttendingDoctorLastName
END
SELECT * FROM @tmpUser

到单个SQL SELECT语句而不使用@tmpUser或任何其他临时表

2 个答案:

答案 0 :(得分:3)

以下使用额外查找,但它满足您的要求。我不确定这是否比使用临时表更有效,但如果UPIN被索引,那么我怀疑它会是。

IF EXISTS(
    SELECT 
        1 
    FROM 
        Users u 
    WHERE 
        u.UPIN = @AttendingDoctorID)
BEGIN
    SELECT 
        u.UserId, 1 
    FROM 
        Users u  WITH(nolock)
    WHERE 
        u.UPIN = @AttendingDoctorID
END ELSE BEGIN
    SELECT
        u.UserId,
        1
    FROM
        Users u (nolock)
    WHERE
        u.FirstName = @AttendingDoctorFirstName AND
        u.LastName = @AttendingDoctorLastName
END

答案 1 :(得分:0)

如何使用OR而不是两个单独的查询。

我认为这符合目的。

SELECT
    u.UserId, 1
FROM
    Users u (nolock)
WHERE
    (u.UPIN = @AttendingDoctorID)
    OR
    (u.FirstName = @AttendingDoctorFirstName AND
    u.LastName = @AttendingDoctorLastName)