How do you insert a record with a nullable column ?
+6
A:
you omit that column from the insert statement, or set it to NULL
northpole
2009-08-12 17:57:11
+5
A:
if column2 is null
insert into table(column1, column3) values (1, 3)
or just include it
insert into table(column1, column2, column3) values (1, null, 3)
Martin
2009-08-12 17:58:27
see my code edit
KM
2009-08-12 21:10:59
@Martin L, see latest edit...
KM
2009-08-13 12:19:44
A:
You guys got me thinking: move -1 to the null indicator, To insert a valid value, move 0 to the null indicator.
Kombucha
2009-08-12 18:01:24
+3
A:
always name all columns in the INSERT. If the table schema changes, your INSERTs are more likely to not break or work wrong. As a result, so just put a NULL in:
INSERT INTO YourTable (col1, col2, col2) VALUES (1, null, 'A')
EDIT
there are many ways for problems to happen, here is just one example of how schema change breaks poorly coded INSERTs:
YourTable
col1 int not null
col2 int null
col3 char(1) null
you code this in several places:
INSERT INTO YourTable VALUES (1, null, 'A')
--OR this ---<<<<EDIT2
INSERT INTO YourTable VALUES (1, 'A') ---<<<<EDIT2
you change your table to:
YourTable
col1 int not null
col1a int null default(0)
col2 int null
col3 char(1) null
what happens with your code? what values go in what columns?
if you had coded it this way
INSERT INTO YourTable (col1, col2, col2) VALUES (1, null, 'A')
it will still work
KM
2009-08-12 18:21:49
I don't understand how adding all columns in will affect anything not breaking. Can you give an example?
Martin
2009-08-12 18:41:00
I thought you meant there was a difference between YourTable(col1, col3) and YourTable(col1, col2, col3). I know your example is bad, I just thought you meant not including col2 was bad.
Martin
2009-08-13 01:53:03
Of course, if you want to use the default value rather than explicitly using null then omitting the column is fine.
KeeperOfTheSoul
2009-08-13 12:30:26
gotcha, I know it was way off topic, but thanks for clearing that up. I'm not a DB guy ... as you can probably tell.
Martin
2009-08-13 12:53:12
@KeeperOfTheSoul, it is hard to add a column, to an existing table, without setting a default value, which is why I put it in my simple example.
KM
2009-08-13 13:02:40