2014-10-03 135 views
0

在VB.Net中,我試圖檢查數據庫中是否已經存在某個值對。如果不是,則需要添加:如何檢查數據庫中是否存在值對?

Public Shared Sub updateChoice(ByVal dbConn As NS.DBConn, ByVal Y As String, ByVal Z As Int32) 
    'check if the Y <=> Z pair already exists 
    Dim sqlText As String = "select from table where X = " & CStr(Y)" and Y =" &CStr(Z) 
    Dim pairExists = dbConn.ExecuteAsDataSet(sqlText) 

    If (pairExists <= 0) Then 
     Dim sqlText As String = "insert into table ..." ' Insert pair into DB 
     dbConn.ExecuteNonQuery(sqlText) 
    End If 
End Sub 

的Visual Studio使我對If (pairExists <= 0) Then的錯誤:Operator <= is not defined for types System.Data.DataSet and Integer

我有一個很難理解這個錯誤。我究竟做錯了什麼?

+1

消息很明確。 pairExists是一個DataSet,而不是一個整數。您無法將這兩種類型進行比較。 – Crowcoder 2014-10-03 09:37:49

+0

那我用錯了嗎?我只是想檢查對是否已經存在,並且需要使用整數或TRUE/FALSE分配pairExists? – Pr0no 2014-10-03 09:39:43

+1

您想要使用ExecuteScalar而不是ExecuteasDataset,但是查詢顯示爲沒有任何列,所以請確保您修復該問題並在select子句中只定義一列。 – Crowcoder 2014-10-03 09:42:53

回答

0

在相同的語句中執行檢查和插入會更有效,它還通過減少檢查和插入之間的時間來顯着降低滿足race condition的機會。你想聲明的是:

MERGE Table WITH (HOLDLOCK) AS t 
USING (VALUES (@X, @Y)) AS s (X, Y) 
    ON s.X = t.X 
    AND s.X = t.Y 
WHEN NOT MATCHED THEN INSERT (X, Y) VALUES (X, Y) 
OUTPUT $action; 

使用MERGEHOLDLOCK是我所知道的,以避免出現競爭狀況的最好方式,但它不是唯一約束的替代品。如果表中的值應該是唯一的,那麼這仍然應該用一個約束來強制執行。然後您可以簡單地檢查返回值ExecuteNonQuery(),如果插入一行,則返回1,如果該對已經存在,則返回0。

您還應該使用參數化查詢!

相關問題