简体   繁体   中英

What's the best (simple) way to UPDATE or INSERT a SQL record in VB.NET

I've been fumbling my way though writing my first application with SQL database access and I've been getting along ok with single commands using system.data.sqlclient.sqlcommand and doing something like:

SQLCmd.CommandText = ("DELETE from ContactRelationships WHERE ID = 'someid'")
SQLCmd.ExecuteNonQuery()

Or to store changes on a form and then save or cancel them:

Dim x As New SqlCommand("DELETE from SharedDataLocations where Location = @Loc and UserID= @UID ;--", cnn)
        x.Parameters.Add("@Loc", SqlDbType.NVarChar, 300).Value = strRemDLoc
        x.Parameters.Add("@UID", SqlDbType.Int).Value = UserID
        PendingSQLChanges.Add(x)
'followed later by
For x = 0 To PendingSQLChanges.Count - 1
            PendingSQLChanges(x).ExecuteNonQuery()
        Next
        PendingSQLChanges.Clear()

I haven't tackled anything more complex than that yet but I'm willing to learn. What I need to do now is take the id for the current STAFF record and see if it is already set in the STAFFMANAGERS relationship table and either update it with the just selected id from the MANAGERS table or create the record if a manager wasn't previously set. Both staff and manager ids are stored in form variables at this point so can just be inserted into any SQL commands.

I've seen various ways I could do this such as adding multiple lines to a SQLCmd.commandtext (although I'm not sure on format for this) but I have no idea if this is a foolproof solution or prone to problems or if it will even work.

Without stretching too far out of my current experience (or giving me an in depth explanation of something more complex) how can I best accomplish this?

I am not sure if this will help but, I have something similar in my VB.NET SQL code. What I did is use a IF THEN statement to check if the record exists. If there is no record then it will INSERT it with a new UID, but if the UID already exists it will UPDATE.

Public Class YourForm
     Private UniqueID as Integer

Private Sub 
    If AddRecord Then 
        SQLCmd.CommandText = "INSERT into YourTableName (YourColumnName1,YourColumnName2) values (" & _
        "'" & YourTextBox.Text & "')")
        Else
           RunSql ("Update YourTableName set YourColumnName='" & YourTextBox.Text & "')" & _
         " where YourUID=" & UniqueID)
End Sub
End Class

也许您需要MERGE语句

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM