Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting NULL to SQL DB from C# DbCommand

Tags:

        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?

like image 572
SkonJeet Avatar asked Mar 21 '12 09:03

SkonJeet


2 Answers

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; 
like image 130
Andrey Gurinov Avatar answered Sep 27 '22 23:09

Andrey Gurinov


Try DBNull.Value

if (!string.IsNullOrEmpty(activity.StaffId))    param.Value = activity.StaffId; else   param.Value=DBNull.Value; 
like image 38
KV Prajapati Avatar answered Sep 28 '22 00:09

KV Prajapati