如果vb.net中不存在则更新

时间:2017-10-17 07:34:47

标签: sql sql-server vb.net

任何人都可以帮我修复我的查询。如果syscode不存在,但是当我尝试更新sysdesc时,我想更新我的数据,因为syscode已经存在而失败了。

    Dim query As String
    Dim rowsAffected As Integer
    query = "UPDATE tbl_sysname SET syscode = @code, sysdesc = @desc " & _
        "WHERE id = @id AND NOT EXISTS  (SELECT syscode FROM tbl_sysname WHERE " & _
        "syscode = @code) "

    cmd = New SqlCommand(query, cn)
    cmd.Parameters.Add("@code", SqlDbType.VarChar).Value = txtCode.Text
    cmd.Parameters.Add("@desc", SqlDbType.VarChar).Value = txtDesc.Text
    cmd.Parameters.Add("@id", SqlDbType.VarChar).Value = lblId.Text

    rowsAffected = cmd.ExecuteNonQuery
    'MsgBox(rowsAffected)

    If rowsAffected >= 1 Then
        'reader = cmd.ExecuteReader
        MsgBox("Update Successfully")
        LVSysName.Items.Clear()
        'reader.Close()
        GetLvData() 'This will display the data of LvSysName
    Else
        MsgBox("Failed to Update")
    End If

我想避免重复syscode,同时我可以更新sysdesc。 帮我修改一下我的问题,或者给我一个关于我应该做什么的建议

1 个答案:

答案 0 :(得分:0)

您需要为此使用两个UPDATE语句。没有办法一气呵成。

UPDATE tbl_sysname 
SET syscode = @code
WHERE id = @id AND 
  NOT EXISTS  (SELECT syscode FROM tbl_sysname WHERE syscode = @code)

UPDATE tbl_sysname 
SET sysdesc = @desc
WHERE id = @id