I have a very simple dynamic SQL query that specifically needs to be called using sp_executesql with parameters. This query works fine in regular dynamic SQL, but fails when using sp_executesql on a conversion error.
I have tried many combinations of dynamic SQL, but none of them seem to work specifically for datetime conversions related to sp_executesql.
declare
@sql_nvarchar nvarchar(max),
@datetime datetime = GETDATE(),
@sqlparams nvarchar(max),
@tablename nvarchar(max) = 'SomeTableName'
Set @sql_nvarchar =
N'
Select *
from ' + @tablename + '
where Date > ''' + convert(nvarchar(23), @datetime, 101) + ''' '
Set @sqlparams =
N'
@datetime datetime,
@tablename nvarchar(max)
'
EXEC(@sql_nvarchar)
EXEC [sp_executesql] @sql_nvarchar,@sqlparams, @datetime, @tablename
The first exec correctly returns the desired query, the second EXEC throws an error: 'Error converting data type nvarchar(max) to datetime.'
Datecolumn ofSomeTableNameis of typedatetime? - Dale K@datetimeto a varchar to compare it with a date for anyway? Its already a date, so you don't need to convert it to anything. Maybe thats the issue? Remove the convert. - Dale K