In this part of your SP:
IF @DateFirst <> '' and @DateLast <> ''
set @FinalSQL = @FinalSQL
+ ' or convert (Date,DateLog) >= ''' + @DateFirst
+ ' and convert (Date,DateLog) <=''' + @DateLast
you are trying to concatenate strings and datetimes.
As the datetime
type has higher priority than varchar
/nvarchar
, the +
operator, when it happens between a string and a datetime, is interpreted as addition, not as concatenation, and the engine then tries to convert your string parts (' or convert (Date,DateLog) >= '''
and others) to datetime or numeric values. And fails.
That doesn't happen if you omit the last two parameters when invoking the procedure, because the condition evaluates to false and the offending statement isn't executed.
To amend the situation, you need to add explicit casting of your datetime variables to strings:
set @FinalSQL = @FinalSQL
+ ' or convert (Date,DateLog) >= ''' + convert(date, @DateFirst)
+ ' and convert (Date,DateLog) <=''' + convert(date, @DateLast)
You'll also need to add closing single quotes:
set @FinalSQL = @FinalSQL
+ ' or convert (Date,DateLog) >= ''' + convert(date, @DateFirst) + ''''
+ ' and convert (Date,DateLog) <=''' + convert(date, @DateLast) + ''''