I'm getting the error
Invalid parameter 1 specified for dateadd.
when I try to execute the following dynamic parametrized query in SQL Server 2012:
DECLARE @Interval nvarchar(5) = 'DAY'
DECLARE @Increment int = 10
DECLARE @BaseDate date = getdate()
DECLARE @ResultDate date
DECLARE @Query nvarchar(2000)
SET @Query = 'SELECT @result = DATEADD(@Interval, @Increment, CAST(@BaseDate AS DATE))'
EXECUTE sp_executesql @Query,
N'@result date OUTPUT, @Interval varchar(50), @Increment int, @BaseDate date',
@Interval = @Interval, @Increment = @Increment,
@BaseDate = @BaseDate, @result = @ResultDate OUTPUT
SELECT @ResultDate
I've changed the SET @Query line to this one.
SET @Query = 'SELECT @result = DATEADD(' + @Interval +', @Increment, CAST(@BaseDate AS DATE))'
Although it works fine, I'm curious about why the first statement is causing the error in my dynamic SQL query?. Doesn't sp_executesql generate the same statement than the concatenated query one?