Inserting NULL to SQL DB from C# DbCommand
Asked Answered
C

4

26
        DbParameter param = comm.CreateParameter();
        param = comm.CreateParameter();
        param.ParameterName = "@StaffId";
        if (!string.IsNullOrEmpty(activity.StaffId))
            param.Value = activity.StaffId;
        param.DbType = DbType.String;
        comm.Parameters.Add(param);

The above does not work (obviously), object not instantiated. I am attempting to insert a NULL into the database when StaffId is NOT populated. How can I achieve this?

Conceive answered 21/3, 2012 at 9:22 Comment(3)
you can use DBNull.ValueTelemark
Perfect! If you post this as answer I'll mark it as correct.Conceive
As for why... https://mcmap.net/q/205220/-what-is-the-point-of-dbnull/…Winterize
T
48

You can use DBNull.Value when you need to pass NULL as a parameter to the stored procedure.

param.Value = DBNull.Value;

Or you can use that instead of your if operator:

param.Value = !string.IsNullOrEmpty(activity.StaffId) ? activity.StaffId : (object)DBNull.Value;
Telemark answered 21/3, 2012 at 9:29 Comment(1)
Thanks for the edit Andrey - appreciate it. It seems crazy to have to cast this as an object though (to me anyway).Conceive
D
8

Try DBNull.Value

if (!string.IsNullOrEmpty(activity.StaffId))
   param.Value = activity.StaffId;
else
  param.Value=DBNull.Value;
Disney answered 21/3, 2012 at 9:24 Comment(2)
is there a way of using the ? operator for a sort of shorthand if else statement here?? It seems to not like the String/DBNull.Value conversion!?Conceive
Try this: param.Value = !string.IsNullOrEmpty(activity.StaffId) ? activity.StaffId : (object)DBNull.Value;Telemark
L
4

You can always use the null-coalescing operator (??)

param.Value = activity.StaffId ?? (object)DBNull.Value;
Lust answered 5/4, 2018 at 18:28 Comment(0)
E
3

You could use DBNull.Value:

param.Value = DBNull.Value;
Ermine answered 21/3, 2012 at 9:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.