查询数据库并插入(如果不存在)

时间:2010-06-21 16:20:57

标签: sql vb.net visual-studio-2010

我想在以下代码中添加一种方法来查看条目是否已存在于已连接的数据库中。如果是,则不添加条目并弹出一个对话框,说明"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

2 个答案:

答案 0 :(得分:1)

您应该能够将输入放入检查冗余的子查询中:

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

答案 1 :(得分: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