0

我的 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
4

1 回答 1

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。

于 2013-05-29T02:33:47.627 回答