I am trying to write a stored procedure in which the where clause needs to be dynamic based on the parameter passed to the procedure.
Based on whether an empty string is passed to StartDate and EndDate, the ContractDate condition selects rows. If they are empty strings, the user would have passed a list of dates(assumption) and I need to select rows that have ContractDates sames as the ones in the list. If the @StartDate and @EndDate params are not empty strings, I select rows that have ContractDate >= @StartDate and <=@EndDate. How will I incorporate this in my proc? The current code results in a syntax error.
select TermDescription,ContractDate,Price,SortOrder into #tbtp from BaseTermPrice
inner hash join Term
on
Term.TermID = BaseTermPrice.TermID
where
BaseID = @BaseID and PeakType = @PeakType and
case when @StartDate != '' and @EndDate != ''
then
ContractDate >= @StartDate and ContractDate <= @EndDate
else
ContractDate in (@DateList)
end
order by
ContractDate,SortOrder