[Python] Error converting data type nvarchar to Datetime while calling stored procedure in...

Discussão em 'Python' iniciado por Stack, Dezembro 28, 2024.

  1. Stack

    Stack Membro Participativo

    I am trying to pass datetime value to a SQL Server stored procedure, but I get this error:


    django.db.utils.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Error converting data type nvarchar to datetime. (8114) (SQLExecDirectW)')
    ​

    Here is the code:

    fromDate = datetime(2022, 1, 1)
    toDate = datetime(2022, 12, 31)
    dealershipId = request.GET['dealershipId']
    cursor = connection.cursor()
    cursor.execute(f"EXEC proc_LoadJobCardbyDateRange [@Fromdate={fromDate}, @Todate={toDate}, @DealershipId={dealershipId}]")
    result = cursor.fetchall()


    I have tried to pass datetime object in order to execute the stored procedure. I also tried to pass datetime as string but the same error persists. I also tried different formats but it didn't work as mentioned in some solutions that I have searched for.

    Also,

    cursor.execute("EXEC proc_LoadJobCardbyDateRange @Fromdate="+fromDate+", @Todate='2022-12-31 00:00:00', @DealershipId="+dealershipId)


    If I pass the date as it is shown in @Todate, it works fine but if I pass it as a variable like I did in @Fromdate case, it throws an error


    django.db.utils.ProgrammingError: ('42000', "[42000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Incorrect syntax near '-'. (102) (SQLExecDirectW)")
    ​

    and if I try to pass it as a datetime object then I got this error:


    TypeError: can only concatenate str (not "datetime.datetime") to str
    ​

    Please guide me as to why I am having this issue and what's the correct solution to this can be?

    Continue reading...

Compartilhe esta Página