SkonJeet
SkonJeet

Reputation: 4905

Inserting NULL to SQL DB from C# DbCommand

        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?

Upvotes: 26

Views: 48905

Answers (4)

Niko Yakimov
Niko Yakimov

Reputation: 83

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

param.Value = activity.StaffId ?? (object)DBNull.Value;

Upvotes: 5

Andrey Gurinov
Andrey Gurinov

Reputation: 2885

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;

Upvotes: 48

Andomar
Andomar

Reputation: 238086

You could use DBNull.Value:

param.Value = DBNull.Value;

Upvotes: 3

KV Prajapati
KV Prajapati

Reputation: 94645

Try DBNull.Value

if (!string.IsNullOrEmpty(activity.StaffId))
   param.Value = activity.StaffId;
else
  param.Value=DBNull.Value;

Upvotes: 8

Related Questions