从 pyoDBC 中的单个查询中检索两个表

retrive two tables from a single query in pyoDBC

多年来这里的第一个问题。 我有一个带有 try catch 的简单查询:

query = f"""
BEGIN TRY
    **a query that can give an error
    with structure:
    insert into TABLE
    primary key
    foreign key ---> that has no match on other tables, giving error**

END TRY

BEGIN CATCH
    SELECT  
        ERROR_NUMBER() AS ErrorNumber  
        ,ERROR_SEVERITY() AS ErrorSeverity  
        ,ERROR_STATE() AS ErrorState  
        ,ERROR_PROCEDURE() AS ErrorProcedure  
        ,ERROR_LINE() AS ErrorLine  
        ,ERROR_MESSAGE() AS ErrorMessage
END CATCH
"""
cursor.execute(query)

AAAAArow = cursor.fetchall()

问题是,如果第一个查询失败,thi 会给出两个 table 的输出:一个空的 window(在 SMSS 中),fetchall 给出一个空列表,以及一个 table 与错误详细信息的一行。 但是 fetchall 只给出第一个查询的空列表作为输出,而不是第二个查询。我如何从单个查询中获取两个不同的 table?

在更专业的同事的帮助下找到了解决方案:

query = f"""
BEGIN TRY
    **a query that can give an error
    with structure:
    insert into TABLE
    primary key
    foreign key ---> that has no match on other tables, giving error**

END TRY

BEGIN CATCH
    SELECT  
        ERROR_NUMBER() AS ErrorNumber  
        ,ERROR_SEVERITY() AS ErrorSeverity  
        ,ERROR_STATE() AS ErrorState  
        ,ERROR_PROCEDURE() AS ErrorProcedure  
        ,ERROR_LINE() AS ErrorLine  
        ,ERROR_MESSAGE() AS ErrorMessage
END CATCH
"""
cursor.execute(query)
AAAAArow = cursor.fetchall()

只需添加:

NEXT = cursor.nextset()
AAAAArow2 = cursor.fetchone()

NEXT 是一个布尔变量,如果有另一个 table 要读取,则值为 TRUE,否则为 false。如果为真,它会自动更改读数 table。所以通过执行第二个 fetchone() 输出将是第二个 table 并继续