简体   繁体   English

如何从SQL Server 2008中的where子句检查表中数据的存在?

[英]How to check existence of data in a table from a where clause in sql server 2008?

Suppose I have a table with columns user_id , name and the table contains data like this: 假设我有一个包含user_idname列的表,并且该表包含如下数据:

user_id   name
-------   -----
sou       souhardya
cha       chanchal
swa       swapan
ari       arindam
ran       ranadeep

If I want to know these users ( sou , cha , ana , agn , swa ) exists in this table or not then I want output like this: 如果我想知道这些用户( souchaanaagnswa )是否存在于此表中,那么我想要这样的输出:

user_id    it exists or not
-------    -----------------
sou            y
cha            y
ana            n
agn            n
swa            y

As ana and aga do not exist in the table it must show "n" (like the above output). 由于anaaga在表中不存在,因此必须显示“ n”(与上面的输出类似)。

Assuming your existing checklist is not on the database, you will have to assemble a query containing those. 假设现有清单不在数据库中,则您将必须汇编包含这些清单的查询。 There are many ways of doing it. 有很多方法可以做到这一点。 Using CTEs, it would look like this: 使用CTE,它看起来像这样:

with cte as
(
select 'sou' user_id
union all
select 'cha'
union all
select 'ana'
union all
select 'agn'
union all
select 'swa'
)
select 
  cte.user_id,
  case when yt.user_id is null then 'n' else 'y' end
from cte
left join YourTable yt on cte.user_id = yt.user_id

This also assumes user_id is unique. 这也假设user_id是唯一的。

Here is the SQLFiddle with the proof of concept: http://sqlfiddle.com/#!3/e023a0/4 这是带有概念证明的SQLFiddle: http ://sqlfiddle.com/#!3/e023a0/4

Assuming you're just testing this manually: 假设您只是手动进行测试:

DECLARE @Users TABLE
(
    [user_id] VARCHAR(50)
)

INSERT INTO @Users 
SELECT 'sou'
UNION SELECT 'cha'
UNION SELECT 'ana'
UNION SELECT 'agn'
UNION SELECT 'swa'



SELECT a.[user_id]
    , [name]
    , CASE
        WHEN b.[user_id] IS NULL THEN 'N'
        ELSE 'Y'
        END AS [exists_or_not]
FROM [your_table] a
LEFT JOIN @Users b
    ON a.[user_id] = b.[user_id]

You didn't provide quite enough information to provide a working example, but this should get you close: 您没有提供足够的信息来提供有效的示例,但这应该可以使您接近:

select tbl1.user_id, case tbl2.user_id is null then 'n' else 'y' end
from   tbl1 left outer join tbl2 on tbl1.user_id = tbl2.user_id
;with usersToCheck as
(
          select 'sou' as userid
    union select 'cha'
    union select 'ana'
    union select 'agn'
    union select 'swa'
)
select utc.userid, 
(case when exists ( select * from usersTable as ut where ut.user_id = utc.userid) then 'y' else 'n' end)
from usersToCheck as utc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM