I have a table like this:
create table1 (field1 int,
field2 int default 5557,
field3 int default 1337,
field4 int default 1337)
I want to insert a row which has the default values for field2 and field4.
I've tried insert into table1 values (5,null,10,null)
but it doesn't work and ISNULL(field2,default)
doesn't work either.
How can I tell the database to use the default value for the column when I insert a row?
Just don't include the columns that you want to use the default value for in your insert statement. For instance:
...will take the default values for
field2
andfield4
, and assign 5 tofield1
and 10 tofield3
.If your columns should not contain
NULL
values, you need to define the columns asNOT NULL
as well, otherwise the passed inNULL
will be used instead of the default and not produce an error.If you don't pass in any value to these fields (which requires you to specify the fields that you do want to use), the defaults will be used:
Try it like this
Then field2 and field4 should have default values.
To insert the default values you should omit them something like this :
All other fields will have null or their default values if it has defined.
The best way is: