开发者

TSQL/SQL 2005/2008 Return Row from one table that is not in othe table

开发者 https://www.devze.com 2023-01-14 02:23 出处:网络
I have to compare a row of one table that is not in another table TableA ID 1 2 3 4 NULL TableB ID 1 4 When comparing TableA with TableB ,the following o/p(NULL Can be ignored)

I have to compare a row of one table that is not in another table

TableA

ID
1
2
3
4
NULL

TableB

ID
1
4

When comparing TableA with TableB ,the following o/p (NULL Can be ignored)

ID   STATUS

1    FOUND   
2    NOT FOUND
3    NOT FOUND
4    FOUND

I 开发者_如何学Gotried with

SELECT
      case T.ID when isnull(T.ID,0)=0 then 'NOT FOUND'
      case T.ID when isnull(T.ID,0)<>0  then 'FOUND'
     end,T.ID 
     FROM
          TableA  T 
               LEFT JOIN
          TableB N 
   ON T.ID=N.ID

Its ended with incorrect syntax near '=',moreover i have no idea whether the query is correct.


Try this:

SELECT a.ID, 
    CASE WHEN b.ID IS NULL THEN 'NOT FOUND' ELSE 'FOUND' END AS Status
FROM TableA a
    LEFT JOIN TableB b ON a.ID = b.ID

Note the difference in the structure of the CASE statement - that was your problem.


To generate the result as shown in the question:

SELECT ID,
       CASE WHEN EXISTS (SELECT * FROM TableB WHERE ID = TableA.ID)
            THEN 'FOUND'
            ELSE 'NOT FOUND'
       END AS STATUS
  FROM TableA

But if you are only interested in the missing records:

SELECT ID
  FROM TableA
 WHERE NOT EXISTS (SELECT * FROM TableB WHERE ID = TableA.ID)


SELECT 
T.ID 
FROM TableA T WHERE NOT EXISTS ( SELECT X.ID FROM TableB X WHERE X.ID = T.ID)

If you want the 'Found' or 'Not Found' answer go for what AdaTheDev posted

0

精彩评论

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

关注公众号