开发者

Replace SQL Query

开发者 https://www.devze.com 2023-03-22 08:00 出处:网络
I want to replace this Query DECL开发者_开发技巧ARE @tmpUser TABLE( UserId INT, UserType INT )

I want to replace this Query

DECL开发者_开发技巧ARE @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

to a single SQL SELECT statement without using @tmpUser or any other temp tables


The following uses an extra lookup, but it fulfills your requirements. I don't know for sure if this is any more efficient than using a temp table, though if UPIN is indexed then I suspect it would be.

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


How about Using OR instead of two separate queries.

I think it would serve the purpose.

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号