code_junkie

T-SQL: Comparing Two Tables - Records that don't exist in second table

Nov 13th, 2011
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. SELECT
  2. P.*
  3. FROM
  4. People P
  5. LEFT OUTER JOIN Employees E ON
  6. E.ID = P.ID -- Or whatever your PK-FK relationship is
  7. WHERE
  8. E.ID IS NULL
  9.  
  10. CREATE TABLE #PEOPLE
  11. (ID INTEGER,
  12. Name NVARCHAR(50))
  13.  
  14. CREATE TABLE #EMPLOYEE
  15. (ID INTEGER,
  16. Name NVARCHAR(50))
  17. GO
  18.  
  19. INSERT #PEOPLE VALUES (1, 'Bob')
  20. INSERT #PEOPLE VALUES (2, 'Steve')
  21. INSERT #PEOPLE VALUES (3, 'Jim')
  22. INSERT #EMPLOYEE VALUES (1, 'Bob')
  23. GO
  24.  
  25. SELECT ID, Name
  26. FROM #PEOPLE
  27. EXCEPT
  28. SELECT ID, Name
  29. FROM #EMPLOYEE
  30. GO
  31.  
  32. SELECT * from PEOPLE, TYPE
  33. WHERE PEOPLE.type_id = TYPE.id
  34. AND TYPE.name = 'CONTRACTOR'
  35.  
  36. SELECT * from PEOPLE, TYPE
  37. WHERE PEOPLE.type_id = TYPE.id
  38. AND TYPE.name = 'EMPLOYEE'
  39.  
  40. SELECT * FROM Table1
  41. WHERE Table1.Key NOT IN (SELECT Table2.Key FROM Table2 WHERE Table2.Key IS NOT NULL)
  42.  
  43. select *(or selected matching field)
  44. from tableA as A
  45. where not exist
  46. (select *(or selected matching field)
  47. from tableB as B
  48. where A.key = B.key)
  49.  
  50. select *(or selected matching field)
  51. from tableA as A
  52. where exist
  53. (select *(or selected matching field)
  54. from tableB as B
  55. where A.key = B.key)
Add Comment
Please, Sign In to add comment