[Python] Call SQL stored procedure using python -> Previous SQL was not a query [duplicate]

Discussão em 'Python' iniciado por Stack, Abril 3, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to call the stored procedure using the python.

    Background: I retrieve the doc_id which I need to pass to stored procedure which is varbinary value. I had the issue where my string doc_id was not converted into varbinary but after fixing it now it throws new error:


    Error executing stored procedure: No results. Previous SQL was not a query.
    ​

    Here is my python code:

    with pyodbc.connect(connection_string) as conn:
    with conn.cursor() as cursor:
    # Execute the SELECT query
    try:
    select_query = "SELECT TOP (1) * FROM [MDW].[MDW_F_PurchaseOrder_attaches] where Document_Id = 333631"
    cursor.execute(select_query)
    select_row = cursor.fetchone()

    # Add the SELECT query result to the response message
    response_message += " SELECT Query Result:\n"
    if select_row:
    response_message += f"{select_row}\n"
    else:
    response_message += " No data found in the SELECT query.\n"

    except Exception as e:
    logging.error(f"Error executing SELECT query: {e}")
    response_message += " Failed to execute SELECT query. Check logs for details.\n"

    # Call the stored procedure with parameters
    try:
    stored_procedure = "EXEC MDW.SP_GetDocument @Hash = ?, @Login = ?"
    cursor.execute(stored_procedure, doc_id_binary, user_email)
    rows = cursor.fetchall()

    # Format the results into a readable string
    response_message += " Stored Procedure Result:\n"
    if rows:
    for row in rows:
    response_message += f"{row}\n"
    else:
    response_message += " No data found for the given parameters.\n"

    except Exception as e:
    logging.error(f"Error executing stored procedure: {e}")
    response_message += " Failed to execute stored procedure. Check logs for details.\n"


    And this is my stored procedure:

    ALTER procedure [MDW].[SP_GetDocument] @Hash varbinary(20),@Login varchar(200)
    as
    set @Hash=isnull(@Hash ,0x36ACEDC6177EA070E533521B02DF279BCBD4BC93)

    select top 1 Source_Db,Document_Id,Displayname
    into #docs
    from MDW.MDW_F_PurchaseOrder_attaches
    where Hash_Document=@Hash

    IF @@ROWCOUNT=0
    select Source_Db=null,Document_Id=null,Displayname=null,_Message='Document not found'
    Else
    select *, _message='OK' from #docs where Document_Id %10=1
    union
    select Source_Db=null,Document_Id=null,Displayname=null,_Message='Not allowed'
    from #docs where Document_Id %10<>1
    GO


    NOTE: Select statement give me the output. Stored procedure has the issue.

    Not sure where it goes wrong. Any help appreciated

    Continue reading...

Compartilhe esta Página