简体   繁体   中英

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_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:

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).

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:

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.

Here is the SQLFiddle with the proof of concept: 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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