这是来自(Update and select in one operation in MSSQL)
的后续问题我有一个列ID
varchar(255)和done
位的表。我获取一个ID
,其中done
位未设置,并在同一步骤中设置该位。然后我将处理ID
并继续下一个..我想这样做,直到没有设置ID
位时没有留下done
。
代码看起来像这样:
import _mssql
con = _mssql.connect(server='server', user='user', password='password', database='default')
con.execute_query('UPDATE tableA SET done=1 OUTPUT INSERTED.ID WHERE ID=(SELECT TOP(1) ID FROM tableA WHERE done=0)')
for row in con:
#row['ID'] is exactly one ID where the done bit wasn't set, but now is.
current_id = row['ID']
while current_id:
start_function(current_id)
else:
print("ALL DONE")
如何在while [...]
中获取,分配和检查上述查询?
例如在伪代码中:
while(current_id = row['ID'] for row in con.execute_query([...]):
start_function(current_id)
else:
print("ALL DONE")
使用Microsoft SQL Server Enterprise Edition v9.00.3042.00,即SQL Server 2005 Service Pack 2
答案 0 :(得分:0)
我想我有一个解决方案。至少它似乎对我有用。
我必须遵循两个功能:
def get_next(con):
con.execute_query('UPDATE tableA SET done=1 OUTPUT INSERTED.ID WHERE ID=(SELECT TOP(1) ID FROM tableA WHERE done=0)')
for row in con:
#row['ID'] is exactly one ID where the done bit wasn't set, but now is.
current_id = row['ID']
return current_id
def start_function(id):
#do something here with the id.
pass
然后在主
import _mssql
con = _mssql.connect(server='server', user='user', password='password', database='default')
id = get_next(con)
while current_id:
start_function(id)
id = get_next(con)
else:
print("ALL DONE")