Reputation: 11
In SQL Server 2014 ...
I am trying to find the rows in table 'new' that do not exist in table 'old'. I want to take these new rows and stuff them into a third table that I create. Table 'new' has a primary key composed of two columns, MakeId and ModelId. The following SQL runs, but gives me vastly too many rows. Obviously, I am doing something wrong.
select
new.MakeId ,
new.MageMakeId ,
new.ModelId ,
new.MageModelId
into BiUpdater..TranslateModel
from Mage_Production..TranslateModel new
left outer join BiLoader..TranslateModel old0 on new.MakeId = old0.MakeId
left outer join BiLoader..TranslateModel old1 on new.ModelId = old1.ModelId
go
Upvotes: 0
Views: 124
Reputation: 7407
There is a SQL statement called EXCEPT that does this. here is a link- http://msdn.microsoft.com/en-us/library/ms188055.aspx
Your right hand table would be 'new' and your left hand table would be 'old'.
select *
into BiUpdater..TranslateModel
from (
select new.*
from Mage_Production..TranslateModel new
EXCEPT
select old.*
from BiLoader..TranslateModel old
)
Alternatively you could use a left join to do this:
select new.*
into BiUpdater..TranslateModel
from Mage_Production..TranslateModel new left join BiLoader..TranslateModel old
on new.MakeId = old.MakeId and new.ModelId = old.ModelId
where old.MakeId is null
Upvotes: 0
Reputation: 1270091
My guess is that you want only one join using both columns:
select new.MakeId, new.MageMakeId, new.ModelId, new.MageModelId
into BiUpdater..TranslateModel
from Mage_Production..TranslateModel new left outer join
BiLoader..TranslateModel old
on new.MakeId = old.MakeId and new.ModelId = old.ModelId
where old.MakeId is null;
More importantly, though, you need the where
clause to get the non-matches.
EDIT:
If you are looking for rows that don't match either MakeId
or ModelId
, then perhaps this is really what you want:
select new.MakeId, new.MageMakeId, new.ModelId, new.MageModelId
into BiUpdater..TranslateModel
from Mage_Production..TranslateModel new left outer join
BiLoader..TranslateModel old1
on new.MakeId = old1.MakeId left join
BiLoader..TranslateModel old2
on new.ModelId = old2.ModelId
where old1.MakeId is null and old2.ModelId is null;
You might want an or
instead of and
, in which case use select distinct
.
Upvotes: 2