Sunday, February 19, 2012

default value not function

I have set a column A in table test with default value = 0 (money data type)
and not allow null, but when I run my application and want to save the
record, there is an error like ...cannot
insert value Null into column A table test, column does not allow null,
insert fail..., why the default value 0 not function (why there is null
insert', not 0 insert)Hi
The default will only be used if you don't specify a value for the column or
if you use the default keyword.
e.g.
CREATE TABLE MyTest ( id int not null ,
val char(1) not null default 'A' )
INSERT INTO MyTest ( id ) VALUES ( 1 )
-- (1 row(s) affected)
INSERT INTO MyTest ( id, val ) VALUES ( 2, 'C' )
-- (1 row(s) affected)
INSERT INTO MyTest ( id, val ) VALUES ( 3, DEFAULT )
-- (1 row(s) affected)
INSERT INTO MyTest ( id, val ) VALUES ( 4, NULL )
/*
Server: Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column 'val', table 'tempdb.dbo.MyTest';
column does not allow nulls. INSERT fails.
The statement has been terminated.
*/
INSERT INTO MyTest ( id, val ) VALUES ( 4, ISNULL(NULL,'A') )
--(1 row(s) affected)
SELECT * FROM MyTest
/*
id val
-- --
1 A
2 C
3 A
4 A
(4 row(s) affected)
*/
John
"tong" wrote:
> I have set a column A in table test with default value = 0 (money data type)
> and not allow null, but when I run my application and want to save the
> record, there is an error like ...cannot
> insert value Null into column A table test, column does not allow null,
> insert fail..., why the default value 0 not function (why there is null
> insert', not 0 insert)
>

No comments:

Post a Comment