替换 SQL 查询

发布于 2024-11-25 17:23:11 字数 525 浏览 1 评论 0原文

我想将此查询替换

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 或任何其他临时表

I want to replace this Query

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

柠檬色的秋千 2024-12-02 17:23:11

以下使用了额外的查找,但它满足您的要求。我不确定这是否比使用临时表更有效,但如果 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

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
梓梦 2024-12-02 17:23:11

使用 OR 而不是两个单独的查询怎么样?

我认为这会达到目的。

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

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文