Skip to content
Advertisement

Dynamic SQL stored procedure and datetime

I have a simple query that I want to convert to dynamic SQL. I have 2 input parameters: a table and a datetime. And the output is the rowcount for the table and this specific datetime.

I tried different solutions. I tried the query with execute sp_executesql, I tied to add the the ”’ before and after the @P_LOAD_DATE. I am probably missing something here.

When I execute the stored procedure with a table name and datetime like 2021-05-06 06:41:52.557, I get the following error:

Conversion failed when converting date and/or time from character string.

But why?

I even tried to add a conversion to datetime like this, but I still get the same error.

But when I execute SELECT convert(datetime, ‘2021-05-06 06:41:52.557’) it works out fine. I am just confused right now and can’t find the root of the problem.

Edit: valid_from is a datetime in the target table. So that is also not the reason for the problem

Advertisement

Answer

You need to properly and safely inject your dynamic object name and parametrise your parameter:

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement