2014-10-28 41 views
0

我有一個表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

+1

你想看看**交易**和**行鎖定爲此。在'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

+0

我有一個單一的execute_quer()的解決方案..我現在編輯問題並添加我的解決方案。但非常感謝你的鏈接。 – 2014-10-28 09:24:54

回答

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']) 
1

這個怎麼樣?

UPDATE tableA SET done = 1 WHERE ID = (SELECT TOP 1 ID FROM tableA WHERE done = 0) 
+0

看起來不錯,但我認爲我不能'con for:start_function(row ['ID'])''中的行。爲了澄清我自己,它做了它應該做的事情,但是我沒有得到ID,我只是設置了完成位。 – 2014-10-28 07:46:20