2010-06-21 58 views
0

我想添加一種方法來查看下面的代碼中是否已經存在連接的數據庫中。如果是,則不要添加條目並彈出一個對話框,說明"already been scanned"的影響,如果不是,則照常進行。查詢數據庫並插入(如果不存在)

Using connection As New SqlClient.SqlConnection("Data Source=XXXXX;Initial Catalog=XXXXXX;Integrated Security=True;Pooling=False;Encrypt=False"), _ 
    cmd As New SqlClient.SqlCommand("INSERT INTO [XXXXX] (TrackingNumber, Date) SELECT @TrackingNumber, @Date WHERE NOT EXISTS (SELECT * FROM([XXXXX])WHERE TrackingNumber = @TrackingNumber AND Date = @Date)", connection) 
     cmd.Parameters.Add("@TrackingNumber", SqlDbType.VarChar, 50).Value = TrNum 
     cmd.Parameters.Add("@Date", SqlDbType.DateTime, 8).Value = TrDate 
     connection.Open() 
     cmd.ExecuteNonQuery() 
     connection.Close() 
End Using 

回答

0

我VB.NET可能有點過,但希望這應該給一般的想法!

Dim rowsAffected AS Integer 

    Using connection As New SqlClient.SqlConnection("Data Source=XXXXX;Initial Catalog=XXXXXX;Integrated Security=True;Pooling=False;Encrypt=False"), _ 
     cmd As New SqlClient.SqlCommand("INSERT INTO [XXXXX] (TrackingNumber, Date) SELECT @TrackingNumber, @Date WHERE NOT EXISTS (SELECT * FROM [XXXXX] WHERE TrackingNumber = @TrackingNumber)", connection) 
     cmd.Parameters.Add("@TrackingNumber", SqlDbType.VarChar, 50).Value = TrNum 
     cmd.Parameters.Add("@Date", SqlDbType.DateTime, 8).Value = TrDate 
     connection.Open() 
     rowsAffected = cmd.ExecuteNonQuery() 
     connection.Close() 
    End Using 


If rowsAffected = 0 Then 
MsgBox "Scanned Already" 
Else 
MsgBox "Inserted Succesfully" 
End If 
+0

工作正常!謝謝一堆! – 0bfus 2010-06-21 18:56:29

+0

@Martin Smith更快速的一件事,任何原因都不允許字母和數字輸入? – 0bfus 2010-06-22 13:39:58

+0

@ 0bfus我看不出任何理由爲什麼會這樣。 @TrackingNumber是varchar(50),所以應該允許使用字母。它會給你一個錯誤? – 2010-06-22 13:52:12

1

你應該能夠把你的投入,用於檢查冗餘的子查詢:

INSERT INTO [XXXXXXX] (TrackingNumber, Date) 
    SELECT @TrackingNumber, @Date from DUAL 
    WHERE NOT EXISTS (
     SELECT * 
     FROM [XXXXXXX] 
     WHERE TrackingNumber = @TrackingNumber AND Date = @Date) 
+0

我得到一個SqlException是在cmd.ExecuteNonQuery的無效對象名稱DUAL的未處理的錯誤。在原來的代碼中會放置一個子查詢? – 0bfus 2010-06-21 16:45:33

+1

@ 0bfus - 對於SQL Server,只需從'DUAL'中刪除''''就可以得到受影響的行作爲'cmd.ExecuteNonQuery'的返回值。如果零沒有改變。 – 2010-06-21 16:57:24

+0

使用上面的代碼我得到一個SQL異常是在cmd.ExecuteNonQuery()說未正確的語法附近未處理的錯誤)。我更新了我的問題中的代碼,以顯示迄今爲止我所做的更改。 – 0bfus 2010-06-21 17:12:36

相關問題