TSQL Comparing two Sets

后端 未结 6 2118
野的像风
野的像风 2021-01-18 03:58

When two sets are given

s1 ={ a,b,c,d} s2={b,c,d,a}

(i.e)

TableA

Item
a
b
c
d

TableB

Item
b
c
d
a

How to write Sql quer

6条回答
  •  春和景丽
    2021-01-18 04:54

    Something like this, using FULL JOIN:

    SELECT
      CASE 
        WHEN EXISTS (
          SELECT * FROM s1 FULL JOIN s2 ON s1.Item = s2.Item
          WHERE s1.Item IS NULL OR s2.Item IS NULL
          )
        THEN 'Elements in tableA and tableB are not equal'
        ELSE 'Elements in tableA and tableB are equal'
      END
    

    This has the virtue of short-circuiting on the first non-match, unlike other solutions that require 2 full scans of each table (once for the COUNT(*), once for the JOIN/INTERSECT).

    Estimated cost is significantly less than other solutions.

提交回复
热议问题