首页 > 解决方案 > python 使用 query_1 导致 query_2 where 条件,因为这两个查询都将在不同的 sql server 中运行

问题描述

python 使用 query_1 导致 query_2 where 条件,因为这两个查询都将在不同的 sql server 中运行

cnxn = pyodbc.connect(driver = '{SQL Server}', host = 'server1', database = 'db1', user = '', password = '', Trusted_Connection = 'yes')
cursor = cnxn.cursor()

cnxn1 = pyodbc.connect(driver = '{SQL Server}', host = 'server2', database = 'db2', user = '', password = '', Trusted_Connection = 'yes')
cursor1 = cnxn1.cursor()


query = "SELECT top(10) Batch_ID   FROM [db1].[dbo].[table1];"

cursor.execute(query)
Result = cursor.fetchall()

print (Result)

query1="delete FROM [db2].[dbo].[table2] where Batch_ID in (**Result**);" ###i have use 1st query result in this where condition

cursor.execute(query1)
Result1 = cursor1.fetchall()

标签: pythonpython-3.xpypyodbc

解决方案


你真的不需要IN为你的陈述构建一个子句DELETE。您可以只使用常规... WHERE Batch_ID = ?,然后将值列表传递给.executemany,例如

query = "SELECT TOP(10) Batch_ID FROM [db1].[dbo].[table1];"
cursor.execute(query)
result = cursor.fetchall()
query1 = "DELETE FROM [db2].[dbo].[table2] WHERE Batch_ID = ?;"
cursor.executemany(query1, result)

推荐阅读