Inserting NULL to SQL DB from C# DbCommand

别来无恙 提交于 2019-12-14 00:28: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?


回答1:


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;



回答2:


Try DBNull.Value

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



回答3:


You could use DBNull.Value:

param.Value = DBNull.Value;



回答4:


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

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


来源:https://stackoverflow.com/questions/9801649/inserting-null-to-sql-db-from-c-sharp-dbcommand

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!