我正在編寫一個應用程序,它將插入如果找不到主鍵或更新,如果它被發現。 這是在本網站上詢問here的相同類型的情況。更新如果退出或插入,如果不是
問題。
現在我正在使用下面的代碼插入。 (名稱已更改,但格式相同)
Using con As New SqlConnection
Using cmd As New SqlCommand
Try
con.ConnectionString = "removed"
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO [table] ([primary key],[value]) VALUES (@primary key, @value)"
cmd.Parameters.AddWithValue("@primary key", code to grab key)
cmd.Parameters.AddWithValue("@value", code for value)
cmd.ExecuteNonQuery()
con.Close()
Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
End Try
End Using
End Using
上面的完整代碼適用於我。 但現在我需要它只做插入的主鍵沒有找到。
基於上面的鏈接,是答案做這樣的事
cmd.CommandText = "Merge Table as target using (values ('key') as source(key) on taget.idfield = code for key...
這感覺不對我說,(可能是因爲它的所有在一行上)。什麼是完成此任務的最佳方式?
寫一個'select',然後是一個'update'或'insert'取決於它是否存在有什麼問題? – paqogomez
這是我的第一個想法,但我想確保這是正確的做法。 – Itomship
我想你會發現'合併'雖然整潔,但隨着時間的推移難以維持。 KIS - 保持簡單。 – paqogomez