I tried to figure out a dynamic query to get date col within past 20 days. The idea is quite simple and, moreover, I know the table does contain dates from getdate() to -20 days but still no result get returned
DECLARE @date_past_period varchar(MAX);
DECLARE @date_past_number varchar(MAX);
SET @date_past_period='day';
SET @date_past_number='20';
DECLARE @aDate datetime;
DECLARE @sql varchar(MAX);
SET @sql='SELECT date FROM table WHERE convert(varchar,date,121) BETWEEN convert(varchar,getdate(),121) AND convert(varchar,dateadd('+@date_past_period+', -'+@date_past_number+', getdate()),121)';
exec(@sql);
Maybe the problem is in dynamic thing but I am not sure.
Any useful comment is appreciated
I am pretty sure this scenario can be covered without using dynamic SQL, however, one obvious problem in your SQL is the between clause – the range is in the wrong order. Try changing your @sql as below: