Hi, While messing about trying to work out a way so that when a field does not have any data for a parameter all records are returned I stumbled along:
declare @schcode varchar(2)
SET @schcode = '13'
--returns records for 13 (13 is a valid school)
select * FROM udw.division as d
left join (select school_code from udw.school where school_code = @schcode)
as s on s.school_code = s.school_code
where d.school_code = isnull(s.school_code,d.school_Code)
--returns records for all schools (X is NOT a valid school)
SET @schcode = 'X'
select * FROM udw.division as d
left join (select school_code from udw.school where school_code = @schcode)
as s on s.school_code = s.school_code
where d.school_code = isnull(s.school_code,d.school_Code)
Now what I am trying to understand is why this works. Why would self joining the nested query and then using isnull allow code to return matching records where valid and non matching valids when NULL?
Just curious if anyone can explain why.
Cheers
declare @schcode varchar(2)
SET @schcode = '13'
--returns records for 13 (13 is a valid school)
select * FROM udw.division as d
left join (select school_code from udw.school where school_code = @schcode)
as s on s.school_code = s.school_code
where d.school_code = isnull(s.school_code,d.school_Code)
--returns records for all schools (X is NOT a valid school)
SET @schcode = 'X'
select * FROM udw.division as d
left join (select school_code from udw.school where school_code = @schcode)
as s on s.school_code = s.school_code
where d.school_code = isnull(s.school_code,d.school_Code)
Now what I am trying to understand is why this works. Why would self joining the nested query and then using isnull allow code to return matching records where valid and non matching valids when NULL?
Just curious if anyone can explain why.
Cheers