2012-09-13 42 views
2

我在測試如何通過單擊按鈕更新最新數據庫條目中的特定列時出現此錯誤。之前,我設置更新語句OleDbException:查詢表達式'@bottlecount ORDER BY ID DESC'中的語法錯誤(缺少運算符)

Dim statement As String = "UPDATE tblPatientInfo SET bottle_used = @bottlecount" 
statement &=" WHERE room_number =1" 

但在數據庫中的所有條目更新,這就是爲什麼我試着去使用ORDER BY ID DESC,ID是主ID。該程序應該得到最新的數據庫條目,它只會更新bottle_used。一旦使用它,我得到一個OleDbException。

這是我的代碼:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
    '====test number of bottles============= 
    Form5.lblBottle.Text = Form5.lblBottle.Text + 1 

    Dim statement As String = "UPDATE tblPatientInfo SET bottle_used = @bottlecount ORDER BY ID DESC" 

    Dim cmd As New OleDbCommand 

    With cmd 

     .Connection = Conn 
     .CommandType = CommandType.Text 
     .CommandText = statement 
     .Parameters.AddWithValue("@bottlecount", Form5.lblBottle.Text) 

     Conn.Open() 
     .ExecuteNonQuery() 
    End With 
    Conn.Close() 

End Sub 

任何幫助,將不勝感激。謝謝!

回答

2

似乎要與最大ID值更新的行。 DMax function應該使這個很簡單。

UPDATE tblPatientInfo 
SET bottle_used = @bottlecount 
WHERE ID = DMax('ID', 'tblPatientInfo') 
1

基本上,您不能直接在update語句中添加ORDER BY子句。您可以通過order by創建update聲明的唯一方法是使用order by子句創建select子查詢。例如,

UPDATE messages 
SET status=10 WHERE ID in 
    (
    SELECT ... 
    FROM ... 
    WHERE ... 
    ORDER BY priority 
    ) 

也許你想這個,

UPDATE tblPatientInfo 
SET bottle_used = @bottlecount 
WHERE ID = 
    (
     SELECT MAX(ID) maxID 
     FROM tblPatientInfo 
     WHERE room_number = 1 
    ) 
+0

什麼是語法?抱歉。我是VB新手。謝謝! –

+0

@CatherineTakishima我剛剛更新了答案。 –

+0

@CatherineTakishima你正在使用什麼版本的訪問? –

相關問題