是否可以使用现有的INSERT代码并让它执行相同的操作但更新?
示例是:
ID | formTitle1 | formTitle2 | formTitle3 | formTitle4
-------------------------------------------------------
20 | The Rock | Booker | The Vine | Keys
如果我想更新所有4行,那么我想我可以这样做吗?:
sql = "UPDATE formSettings " & _
"SET (formTitle1, formTitle2, formTitle3, formTitle4) " & _
"VALUES (@formTitle1, @formTitle2, @formTitle3, @formTitle4) " & _
"WHERE ID = '" & theID & "'"
Dim updateCmd As New SqlCommand(sql, myCONN)
updateCmd.Parameters.Add("@formTitle1", SqlDbType.VarChar)
updateCmd.Parameters.Add("@formTitle2", SqlDbType.VarChar)
updateCmd.Parameters.Add("@formTitle3", SqlDbType.VarChar)
updateCmd.Parameters.Add("@formTitle4", SqlDbType.VarChar)
updateCmd.Parameters("@formTitle1").Value = "changed1"
updateCmd.Parameters("@formTitle2").Value = "changed2"
updateCmd.Parameters("@formTitle3").Value = "changed3"
updateCmd.Parameters("@formTitle4").Value = "changed4"
myCONN.Open()
updateCmd.ExecuteScalar()
myCONN.Close()
应更新为:
ID | formTitle1 | formTitle2 | formTitle3 | formTitle4
-------------------------------------------------------
20 | changed1 | changed2 | changed3 | changed4
我知道我的UPDATE语法错误,但我不确定这是否可行?
答案 0 :(得分:5)
您的更新语法无效,应为
sql = "UPDATE formSettings " & _
"SET formTitle1 = @formTitle1, formTitle2 = @formTitle2, formTitle3 = @formTitle3, formTitle4 = @formTitle4 " & _
"WHERE ID = @ID"
并参数化了您的ID
,现在您将拥有5个参数
还会将您的代码重组为此内容,
USING
声明片段,
Dim _sql As String = "UPDATE formSettings " & _
"SET formTitle1 = @formTitle1, formTitle2 = @formTitle2, formTitle3 = @formTitle3, formTitle4 = @formTitle4 " & _
"WHERE ID = @ID"
Using conn As New SqlConnection("connectionStringHere")
Using comm As New SqlCommand()
With comm
.Connection = conn
.CommandType = CommandType.Text
.CommandText = _sql
.Parameters.AddWithValue("@formTitle1", "changed1")
.Parameters.AddWithValue("@formTitle2", "changed2")
.Parameters.AddWithValue("@formTitle3", "changed3")
.Parameters.AddWithValue("@formTitle4", "changed4")
.Parameters.AddWithValue("@ID", theID)
End With
Try
conn.Open()
comm.ExecuteNonQuery()
Catch ex As SqlException
' do something on the error
' do not hide it!
End Try
End Using
End Using
SOURCES
答案 1 :(得分:1)
UPDATE tbl
SET Field1 = @Value1, Field2 = @Value2
WHERE ....