0

I have an application that when I run an update statement, on a given condition a value must be set to null.

I am using StringBuilder to create my sql string and I can't a value to set to null. Given that I've used the DBNull.Value and it's inserting a blank string ("") into the database instead of null can you insert a null value into a database using a stringbuilder and an execute query statement?

Here is what I am using. I have tried just .Append(DBNull.Value) but a query won't execute like that because it doesn't put anything there so the query ends up like

... , [lastRunProcessGUID] = where ... (using Nothing results in the same thing)

With psSql
    .Append("update [connection string] ")
    .Append("set [Status] = ")
    .Append("'" & newStatus & "' ")

    If newStatus.Equals("0") Then
        .Append(", [lastRunProcessGUID] = ")
        .Append("'" & DBNull.Value & "'")
    End If

    .Append(" where [workItemID] = ")
    .Append("'" & workItemID & "' AND")
    .Append("' [StepLogID] = ")
    .Append("'" & stepLogID & "'")
End With
8
  • I could be dead wrong (hence leaving it as a comment), but I think replace .Append("'" & DBNull.Value & "'") with .Append("NULL") - no text delimiters - Just explicitly stating the value NULL. Commented Apr 17, 2014 at 20:12
  • NO, you can't! Well, you can, but only if you don't care if your program gets hacked. And for that matter, your existing non-null parameters are still going to get you hacked, probably sooner rather than later. Commented Apr 17, 2014 at 20:14
  • Be VERY careful of SQL injection, when building dynamic SQL like this. Commented Apr 17, 2014 at 20:15
  • 1
    @JohnBustos Where you think variables like newStatus get populated from? All data comes from the user at some point. Commented Apr 17, 2014 at 20:16
  • 1
    the application is internal for the dev team so i'm not too worried about sql injection. but thanks for the concern. Commented Apr 17, 2014 at 20:23

1 Answer 1

2

Because you are building the SQL statement as a string just write the syntax as you would using Mgmt-Studio

if newStatus.Equals("0") Then
    .Append(", [lastRunProcessGUID] = NULL")
End If

DbNull.Value is more useful when performing logic when reading a value from the DB.

if ( rdr["col"] == DbNull.Value ) { ... }

I would change your code to use Parameterized SQL to prevent SQL Injection or use stored procedures instead of dynamic SQL generated from the application, if possible or appropriate.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.