create procedure sp_getfreq(in @brandid integer, in @rcode char(2)) result (sortcode char(1), descrp char(30), siteno char(2), freqcode char(2),frequency smallint, firstfreq smallint, numfirstloads smallint, checkscale tinyint) begin declare @freqcode char(2) ; declare @frequency smallint ; declare @firstFreq smallint ; declare @numfirstloads smallint ; declare @checkscale smallint ; select freqcode, frequency, firstFreq, numfirstloads, checkscale into @freqcode, @frequency, @firstFreq, @numfirstloads, @checkscale from samplefreqs where brandid = @brandid and rcode = @rcode and sortcode = '*' ; if @freqcode is not null then select s.sortcode, s.descrp, s.siteno, sf.freqcode, sf.frequency, sf.firstfreq, sf.numfirstloads, sf.checkscale from samplefreqs sf join sortcodes s on sf.sortcode = s.sortcode and sf.rcode = s.rcode where sf.brandid = @brandid and sf.rcode = @rcode union select s.sortcode, s.descrp, s.siteno, @freqcode as freqcode, @frequency as frequency, @firstFreq as firstfreq, @numfirstloads as numfirstloads, @checkscale as checkscale from sortcodes s where not exists (select * from samplefreqs sf where sf.sortcode = s.sortcode and sf.rcode = s.rcode and sf.brandid = @brandid ) and s.rcode = @rcode else select s.sortcode, s.descrp, s.siteno, sf.freqcode, sf.frequency, sf.firstfreq, sf.numfirstloads, sf.checkscale from samplefreqs sf join sortcodes s on sf.sortcode = s.sortcode and sf.rcode = s.rcode where sf.brandid = @brandid and sf.rcode = @rcode end if ; end>Sorry, but I'm not clear on what you want. Do you want to cross join Sites with SortCodes and add Frequency for each combination? Something like
Select st.site, st.description, sc.sortno, sc.descripton > (SELECT TOP 1 Frequency > FROM SampleFrequency > WHERE (Site = st.Site Or Site = '*') AND > (Sortno = sc.Sortno Or Sortno = '*') > ORDER BY Site DESC, Sortno Desc)) AS Frequency > FROM sites st CROSS JOIN SortCodes sc >>
DECLARE @Site char(1), @Sortno Char(1) >>>SET @Site = '2' >>>SET @Sortno = 'B' >>>SELECT TOP 1 Site, Sortno, Frequency >>> FROM SampleFrequency >>> WHERE (Site = @Site Or Site = '*') AND >>> (Sortno = @Sortno Or Sortno = '*') >>> ORDER BY Site DESC, Sortno Desc >>> >>>* Test Data >>>1 A 20% >>>* * 100% >>>2 * 30% >>>* B 40% >>>3 B 50% >>>* Result : >>>2 * 30% >>>As you can see the Site takes precedence over Sortno in case of conflict. You can change it to your req's.