Wednesday, 21 August 2013

SQL Union exclude row if value already exists in first table

SQL Union exclude row if value already exists in first table

I have two tables which i wish to combine. However, there is a field in
both tables that should have the same value in the second table the second
tables record should be excluded.
These are a MSSQL 2012 tables.
The only way i can think of is something nasty like this.
Select A, B from Tab1 Union Select C, D from Tab2 where Tab2.c not in
(Select A from Tab1)
It looks relatively clean in my example but the selects for Tab1 and tab2
have long and complex where clauses and i would need to duplicated that in
the "not in" select statement.
I've seen other solutions but not in MSSQL. Any one out there have a
better example ?
Thanks

No comments:

Post a Comment