不一样的 Null

  前不久处理一个异常的时候发现了一段有趣的代码,一同事在往表里(Sql Server 数据库)添加数据的时候给可以为 null 的字段赋了如下的值:

Student stu = new Student();
stu.Name = "晓菜鸟";
stu.Age = 21;
stu.RegTime = (DateTime)System.Data.SqlTypes.SqlDateTime.Null;
stu.Remark = (string)System.Data.SqlTypes.SqlString.Null;
stuService.Add(stu);

  问题出现在读取数据上,读取的时候判断 Remark != null 竟然成立,然后读取数据就报错了。:( 

    后来我查看数据库记录,发现存储的 Null 和数据库默认的 Null 不一样,在 C# 里面进行比较,得到的结果也证明他们是不一样的 Null 。

  

  总结:我个人觉得根本就不用这么做,假如数据库中 nvarchar 或者 varchar 类型的字段设置了可以为 null,就没必要主动赋 null 值给他,默认的就是null,而对于 DateTime 类型来说,就算你没有在数据库中显示的设置默认值,你插入一个空值进去他保存的也是系统默认时间(1900-01-01)。

  注意:对于 DateTime 类型,插入空值和 Null,结果是不一样的。

//数据库 test 表结构
//Name nvarchar(50)    可以为 null
//CreateTime datetime  可以为 null

string cmdStr = string.Format("insert into [test] VALUES('{0}','{1}')", name, null);//操作结果:默认值 1900-01-01.
string cmdStr = string.Format("insert into [test] VALUES('{0}',null)", name);//操作结果:NULL .
string cmdStr = string.Format("insert into [test] VALUES('{0}','')", name);//操作结果:默认值 1900-01-01.

:)

posted @ 2014-08-15 15:36  晓菜鸟  阅读(306)  评论(0编辑  收藏  举报