Search code examples
sqlbooleansqlparameter

SQL Server : add parameter boolean from vb net into sql as bit


I have a SQL Server database with a table called tblFeatures with 2 columns Feature (Nvarchar(50)) and Setting (bit). I am trying to set the value of this Setting for each Feature via a check box in VB NET. I have tried using True/False 0/1 but have not had luck doing so using SQL parameters. I can do this fine using a normal SQL Update command:

"UPDATE tblSettings SET [Setting]='" & True & "' WHERE Feature='FSCreateTicket'"

However, I want to do it the proper/safe way with SQL parameters. I have scoured Stack and Google results have not found the proper way to get this done. I either get an error, or no error but the value does not get updated.

Here is what I have am currently trying:

Public Function ChangeSetting(ByVal strFeature As String, ByVal bSetting As Boolean)
    Dim sqlcmd As New SqlCommand
    Try
        MYSQL.Open()
        sqlcmd.Connection = MYSQL
        sqlcmd.CommandText = "UPDATE tblSettings SET Setting='@setting' WHERE Feature='@feature'"
        sqlcmd.Parameters.Add("@setting", SqlDbType.Bit).Value = bSetting
        sqlcmd.Parameters.Add("@feature", SqlDbType.NVarChar, 50).Value = strFeature
        sqlcmd.ExecuteNonQuery()

I am getting the error

Conversion failed when converting the varchar value '@setting' to data type bit

I don't understand why it says varchar when the variable sent is boolean and I have declared the SqlDbType as bit.

I have also tried using the AddwithValue parameter without luck.

Public Function ChangeSetting(ByVal strFeature As String, ByVal bSetting As Boolean)
    Dim sqlcmd As New SqlCommand
    Try
        MYSQL.Open()
        sqlcmd.Connection = MYSQL
        sqlcmd.CommandText = "UPDATE tblSettings SET Setting='@setting' WHERE Feature='@feature'"
        sqlcmd.Parameters.AddWithValue("@setting", bSetting)
        sqlcmd.Parameters.Add("@feature", SqlDbType.NVarChar, 50).Value = strFeature
        sqlcmd.ExecuteNonQuery()

This produces no error, but values are not updated. Please help!


Solution

  • Remove the single quotes a around the parameters in your query text, i.e. change

    ...
    sqlcmd.CommandText = "UPDATE tblSettings SET Setting='@setting' WHERE Feature='@feature'"
    ...
    

    to:

    ...
    sqlcmd.CommandText = "UPDATE tblSettings SET Setting=@setting WHERE Feature=@feature"
    ...
    

    When using parameterized queries, quotes will placed if needed you don't have to do it manually and you shouldn't.