Thursday, July 22, 2010

Select Rows from Table1 NOT IN Table2 (t1.a = t2.a and t1.b = t2.b)

--Source(Table1 & Table2)













--Expected OutPut





DECLARE @T1 TABLE(A INT, B INT,C VARCHAR(10))
DECLARE @T2 TABLE(A INT, B INT,C VARCHAR(10))
INSERT INTO @T1(A,B,C)
VALUES (1,1,'SS1')
,(1,2,'SS2')
,(1,3,'SS3')


INSERT INTO @T2(A,B,C)
VALUES (1,1,'SS1')
,(1,2,'SS2')


--Method1:
SELECT A,B
FROM @T1
EXCEPT
SELECT A,B
FROM @T2
--Method2:
SELECT A.A,A.B
FROM @T1 A
left JOIN @T2 B ON A.A = B.A
AND a.B = b.B
WHERE b.B is null
--Method3:
SELECT * FROM @T1 AS T1
WHERE NOT EXISTS (SELECT 0
FROM @T2 AS T2
WHERE T2.A = T1.A
AND T2.B = T1.B
)
 
/*
 
I hope these will give the expected Result, Now i am looking over this which is best?
 
*/

No comments: