Default not working for Alter Table
-
2012年7月5日 21:06
i used the following code to add a column to a table. It was added but the value was set to NULL. I also tried this with no quotes around the 0 so it wouldn't be treated as a string. I don't understand why my default statement didn't work.
ALTER TABLE MyTable ADD MyColumn int NULL DEFAULT '0'
全部回复
-
2012年7月5日 21:14
If you want the default, set it to not allow nulls, otherwise it defaults to NULL:
ALTER TABLE MyTable ADD MyColumn int NOT NULL DEFAULT 0
- 已标记为答案 new to sql server 2012年7月5日 21:21
-
2012年7月5日 21:17
Oh. I thought it would allow nulls but still default to the value I set. No wonder the results were not as I expected. Thanks.
Any idea on what the logic is behind this? Especially since the default was set. I don't understand why the compiler chooses to ignore the default if nulls are allowed.
- 已编辑 new to sql server 2012年7月5日 21:21
-
2012年7月5日 21:24
You need to specify the WITH VALUES clause if you are adding a new column that allows NULLs, but you want that column to be loaded with the default value in the existing rows.
ALTER TABLE MyTable ADD MyColumn int NULL DEFAULT 0 WITH VALUES;
Tom
- 已标记为答案 new to sql server 2012年7月5日 21:29
-
2012年7月5日 21:29AH. Thanks. I forgot about that.
-
2012年7月6日 5:36use replace function and place 0 instead of nulls

