我的SQL表中有一个位字段,如果它设置为0,我需要将其更新为1.我已编写代码为每个条目设置字段,但我需要检查它是否已经为0首先,我可以记录改变的内容。
这是我已经拥有的:
Public Function Update_User_to_TR(ByVal strUserName As String) As String
Dim myUserName As String = strUserName.Trim
Dim myReturn As String
Try
Dim sql As New SQL
Dim strQuery As String
strQuery = "Update dbo.USERS set user_field_Department_TR = 1 where USER_NAME = '" & myUserName & "'"
myReturn = sql.SQLUpdateWT(strQuery)
Catch ex As Exception
myReturn = ex.ToString
MsgBox(myReturn)
End Try
Return myReturn
End Function
答案 0 :(得分:0)
在这种情况下,您应该升级到存储过程或函数,但这是一个示例查询。
"Declare @WillUpdate bit;Set @WillUpdate = 0;" & _
"If Exists(Select user_name from dbo.Users where user_name ='" & myUserName & _
"' and user_field_department_tr = 0 " & _
" Begin " & _
" Update dbo.USERS set user_field_Department_TR = 1 where USER_NAME = '" & myUserName & "';" & _
" Insert Into MyLog(field1, field2) " & _
" Values('sampledata', 'field was updated from 0 to 1');" & _
" End"
但请阅读其他评论并了解sql注入及其如何不好,然后学习如何使用参数化查询,例如ADO.NET。