首页 > 数据库技术 > 详细

SQL Server column not allow Null,insert failed

时间:2014-01-21 09:21:51      阅读:445      评论:0      收藏:0      [点我收藏+]

这个是一个Vendor的应用程序报的错误。,单看这个错误原因很简单,尝试将NULL值插入到表,但是表不允许使用NULL值。

 

查到后面发现其实根本原因是字段的内容没有按照当时的规定。按照要求,用户输入的需要包含’-’,但是用户输入的数据没有这个字符,系统尝试用”-”分隔数据的时候出现问题。

 

其实这个是应用程序设计的问题,在用户输入的时候根据规则验证用户的输入,确保所有的数据都是合理的,这样可以避免后续的问题。(如果不做验证的话,除了业务逻辑的问题,还可能会导致SQL注入的问题)。

 

解决思路:除了在应用端做验证,也可以用SQLServer Constraint

 

下面举个例子:

 

create table test(namevarchar(10))

 

alter table testadd constraintck_nameCHECK(charindex(‘-‘,name)>0)

 

如果我尝试插入没有”-”字符的数据会出现下面的错误:

 

insert into testvalues (‘4‘)

 

Msg 547, Level16, State 0, Line 1

The INSERTstatement conflicted with the CHECK constraint "ck_name". Theconflict occurred in database "master", table "dbo.test",column ‘name‘.

The statement has beenterminated.

有一点要注意保持事物的完整性,如果一次插入多条记录,不用显示事物的话可能会出现有些插入成功,有些失败的情况。为了保持完整性,可以用显事物:

 

begin try

    begin tran

       insert into test values (‘1-‘)

       insert into test values (‘2-‘)

       insert into test values (‘3-‘)

       insert into test values (‘4‘)

       insert into test values (‘5-‘)

    commit tran

end try

begin catch

    rollback tran

end catch

 

这样如果有一条记录有问题就会回滚整个事务。Constraint还可以限制唯一值,外键,用正则表达式等,功能非常强大,数据输入的时候做好验证,可以避免后续很多的维护问题。

 

SQL Server column not allow Null,insert failed

原文:http://blog.csdn.net/kevinsqlserver/article/details/18274881

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!