从C#DbCommand向SQL DB插入NULL [英] Inserting NULL to SQL DB from C# DbCommand

查看:278
本文介绍了从C#DbCommand向SQL DB插入NULL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

        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);

上面的方法不起作用(显然),对象没有实例化.我没有填充StaffId时试图将NULL插入数据库.我该如何实现?

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?

推荐答案

当需要将NULL作为参数传递给存储过程时,可以使用DBNull.Value.

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

param.Value = DBNull.Value;

或者您可以使用它代替您的if运算符:

Or you can use that instead of your if operator:

param.Value = !string.IsNullOrEmpty(activity.StaffId) ? activity.StaffId : (object)DBNull.Value;

这篇关于从C#DbCommand向SQL DB插入NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆