First of all, let's try to see pros and cons of each of 2 approaches:
create view vw_Car1
as
SELECT
c.Id,
case when f.FordId is not null then 'Ford' else 'Chevy' end as Maker,
coalesce(f.Model, ch.Model) as Model
FROM Car as c
LEFT JOIN Ford as f on c.Id = f.FordId
LEFT JOIN Chevy as ch on c.Id = ch.ChevyId
WHERE (f.FordId is not null or ch.ChevyId is not null);
create view vw_Car2
as
select FordId as id, 'Ford' as Maker, Model from Ford
union all
select ChevyId as id, 'Chevy' as Maker, Model from Chevy;
The first one is better when you use it in joins, especially if you'll not using all of your columns. For example, let's say you have a view when you're using your vw_Car
:
create table people (name nvarchar(128), Carid int);
insert into people
select 'John', 1 union all
select 'Paul', 2;
create view vw_people1
as
select
p.Name, c.Maker, c.Model
from people as p
left outer join vw_Car1 as c on c.ID = p.CarID;
create view vw_people2
as
select
p.Name, c.Maker, c.Model
from people as p
left outer join vw_Car2 as c on c.ID = p.CarID;
Now, if you want to do simple select:
select Name from vw_people1;
select Name from vw_people2;
First one would be simple select from people
(vw_Car1
will not be queried at all). Second one will be more complex - Ford
and Chevy
will be both queried.
You could think that first approach is better, but let's try another query:
select *
from vw_people1
where Maker = 'Ford' and Model = 'Fiesta';
select *
from vw_people2
where Maker = 'Ford' and Model = 'Fiesta';
Here second one will be faster, especially if you have index on Model
column.
=> sql fiddle demo - see query plans of these queries.