如何在sqlalchemy中运行多个依赖的sql语句?

问题描述 投票:0回答:1

问题

我有一堆依赖的 SQL 语句,我想在 sqlalchemy 中的相同上下文中运行它们,但我无法使其工作。

同时运行所有内容

values = ', '.join(f"('{id}')" for id in obligor_ids)
q = f"""
    USE {database};
    DECLARE @ObligorIDs AS {schema}.ObligorIDListType;
    INSERT INTO @ObligorIDs (ID) VALUES {values};
    SELECT * FROM {schema}.GetLUsByObligorID(@ObligorIDs);
"""
engine.execute(q)

失败并显示错误消息“此结果对象不返回行。它已自动关闭”,因为无法在一个查询中运行多个批次。我还尝试按照建议的多个位置将字符串包装在“文本”中,但结果相同。当我在 SQL Management Studio 中运行完全相同的查询时,它就像一个魅力。

在会话中逐个运行批次

# Switching to sql function database
q1 = f"USE {database};"

# Declaring input

q2 = f"DECLARE @ObligorIDs AS {schema}.ObligorIDListType;"
q3 = f"INSERT INTO @ObligorIDs (ID) VALUES {values};"

# Declaring output
q4 = f"SELECT * FROM {schema}.GetLUsByObligorID(@ObligorIDs);"

# Running sql function
with Session(engine) as session:
    session.execute(q1)
    session.execute(q2)
    session.execute(q3)
    result = session.execute(q4).fetchall()
    session.commit()

此操作失败,因为 session.execute(q4) 无法访问 @ObligorIDs。

python sql sql-server sqlalchemy subquery
1个回答
0
投票

所以事实证明下面的代码是有效的。但我不知道为什么。

# Switching to sql function database
q1 = f"SET NOCOUNT ON;USE {database};"
with Session(engine) as session:
    session.execute(q1)
    session.commit()

# Insert obligor IDs into the input table
q2 = f"""
    DECLARE @ObligorIDList AS {schema}.ObligorIDListType;
    INSERT INTO @ObligorIDList (ID) VALUES {', '.join(f"('{id}')" for id in obligor_ids)};
    SELECT * FROM {schema}.GetLUsByObligorID(@ObligorIDList);
"""

# Running query
pd.read_sql_query(con=engine, sql=text(q2))
© www.soinside.com 2019 - 2024. All rights reserved.