我有一个列ID
varchar(255)和done
位的表。
我想要获取找到的第一个ID
,其中未设置该位,同时取出也设置该位。因此,该脚本的其他任何实例都不会使用相同的ID
,也不会出现竞争条件。
import _mssql
con = _mssql.connect(server='server', user='user', password='password', database='default')
#these two in a single command
con.execute_query('SELECT TOP 1 ID FROM tableA WHERE done=0')
con.execute_query('UPDATE tableA SET done=1 WHERE ID=\''+id_from_above+'\'')
for row in con:
#row['ID'] contains nothing as it last used with the UPDATE, not the SELECT
start_function(row['ID'])
编辑(包括wewesthemenace的建议):
[...]
con.execute_query('UPDATE tableA SET done = 1 WHERE ID = (SELECT TOP 1 ID FROM tableA WHERE done = 0)')
for row in con:
#row['ID'] contains nothing as it last used with the UPDATE, not the SELECT
start_function(row['ID'])
使用Microsoft SQL Server Enterprise Edition v9.00.3042.00,即SQL Server 2005 Service Pack 2
编辑2:
回答的问题引出了一个后续问题:While mssql query returns an affected ID use it in a while loop
答案 0 :(得分:1)
这个怎么样?
UPDATE tableA SET done = 1 WHERE ID = (SELECT TOP 1 ID FROM tableA WHERE done = 0)
答案 1 :(得分:0)
可能的解决方案,适用于我的情况。
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.
start_function(row['ID'])