Inserting NULL to SQL DB from C# DbCommand

2019-04-18 17:54发布

        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?

标签: c# sql dbcommand
4条回答
成全新的幸福
2楼-- · 2019-04-18 18:17

You could use DBNull.Value:

param.Value = DBNull.Value;
查看更多
The star\"
3楼-- · 2019-04-18 18:18

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

param.Value = activity.StaffId ?? (object)DBNull.Value;
查看更多
萌系小妹纸
4楼-- · 2019-04-18 18:22

Try DBNull.Value

if (!string.IsNullOrEmpty(activity.StaffId))
   param.Value = activity.StaffId;
else
  param.Value=DBNull.Value;
查看更多
SAY GOODBYE
5楼-- · 2019-04-18 18:23

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;
查看更多
登录 后发表回答