我有一個表ID
varchar(255)和done
位。 我想獲取發現的第一個ID
,其中位未設置,同時獲取也設置位。所以沒有其他腳本實例使用相同的ID
,並且沒有競爭條件是可能的。更新和選擇在MSSQL中的一個操作
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企業版v9.00.3042.00工作,即SQL Server 2005的Service Pack 2的
編輯2:
已解答的問題引導我給出後續問題:While mssql query returns an affected ID use it in a while loop
你想看看**交易**和**行鎖定爲此。在'execute_query()'中查找兩個查詢並不容易 - 你很好。「_ solution(afaik)。我發現的好介紹是** [this technet article](http://technet.microsoft.com/en-us/library/jj856598(v=sql.110).aspx)**,介紹它並解釋** ACID **等 – funkwurm 2014-10-28 08:17:52
我有一個單一的execute_quer()的解決方案..我現在編輯問題並添加我的解決方案。但非常感謝你的鏈接。 – 2014-10-28 09:24:54