首页 > 解决方案 > 查询以检查记录是否存在并且表中的列值是否为空

问题描述

给定一个@InvId标识Contact记录的值,然后可以将其连接到UserAccount记录,例如

select *
from UserAccount UA
join Contact as c on UA.email = C.email and C.type = 'Director'
where C.InvId = @InvId

我正在处理两个需要设置标志变量的场景,@userExits如果

  1. Users表中存在匹配的记录,并且该记录中的user_id值为 NULL UserAccount
  2. Users表中不存在匹配的记录

到目前为止,我制定的查询在第二种情况下失败了。

declare @userExits int

if exists (
    select 1
    from UserAccount UA
    join Contact as c on UA.email = C.email and C.type = 'Director'
    where C.InvId = @InvId
    and exists (
        select 1
        from Users U
        where U.email = UA.email 
        and UA.user_id is null
    )
)
set @userExists = 1

用户表:

 user_id | first_name | last_name | email           | telephone
---------------------------------------------------------------
 10      | John       |  Doe      | jdoe@gmail.com  | 123456
 11      | Joe        |  Dane     | jdane@gmail.com | 3456789

联系表:

 contact_id | inv_id | first_name | last_name | email          | type
-------------------------------------------------------------------------
 1          | 100    | john       | Doe       | jdoe@gmail.com | director

用户帐户表:

 s_id | first_name | last_name | email           | username        | user_id
----------------------------------------------------------------------------
 1    | john       | Doe       | jdoe@gmail.com  | jdoe@gmail.com  | 10
 2    | joe        | Dane      | jdane@gmail.com | jdane@gmail.com | null

任何线索将不胜感激。

标签: sqlsql-server

解决方案


根据您在评论中的澄清,我认为您想测试以下 2 个条件:

条件一:User记录存在但user_id为空

select 1
from UserAccount UA
inner join Contact as C on UA.email = C.email and C.[type] = 'Director'
where C.InvId = @InvId
-- User Record exists
and exists (select 1 from Users U where U.email = UA.email)
-- user_id is null
and UA.[user_id] is null

条件2:User记录不存在

select 1
from UserAccount UA
inner join Contact as C on UA.email = C.email and C.[type] = 'Director'
where C.InvId = @InvId
-- User Record doesn't exist
and not exists (select 1 from Users U where U.email = UA.email)

这些可以与 a 结合OR来测试这两个条件,如下所示:

declare @userExists int;

if exists (
  select 1
  from UserAccount UA
  inner join Contact as C on UA.email = C.email and C.[type] = 'Director'
  where C.InvId = @InvId
  and (
    (UA.[user_id] is null and exists (select 1 from Users U where U.email = UA.email))
    or not exists (select 1 from Users U where U.email = UA.email)
  )
)
begin
  set @userExists = 1;
end;

顺便说一句,变量真的应该被调用@userExists吗?不是@userNotExists吗?

注意 1:有必要知道然后使用该变量来做什么@userExists- 例如,如果您使用它来更新记录,那么很可能更新和测试可以组合成一个语句。

注2:我必须假设这仅用于测试目的?因为不推荐使用电子邮件地址加入 - 除非您准备对电子邮件地址设置唯一限制,但有些人仍然共享电子邮件地址。

注意 3:最好的做法是在表格命名中保持一致,以确定您是使用单数形式还是复数形式。你用过Users(复数)和Contact(单数)。


推荐阅读