Question

I understand that when adding a column to a table containing data in SQL server, the column must have a NULL option or a default. Otherwise what would SQL Server pad the new rows with?

I am at a loss as to why I can't add a NOT NULL column to an empty table however. I have tried this on two instances of SQL 2008 and one instance of SQL 2005 with no problems. However a customer with SQL 2000 does have this problem. Is this related to SQL 2000 or is it an option you can turn off. Let's hope it's an option.

Select @@Version

Microsoft SQL Server 2000 - 8.00.760 (Intel X86) Dec 17 2002 14:22:05 Copyright (c) 1988-2003 Microsoft Corporation Developer Edition on Windows NT 5.1 (Build 2600: Service Pack 3)

Select count(*) from actinv

0

ALTER TABLE [ActInv] ADD [BATCHNUMBER] NVARCHAR(50) NOT NULL

Msg 4901, Level 16, State 1, Line 1 ALTER TABLE only allows columns to be added that can contain nulls or have a DEFAULT definition specified. Column 'BATCHNUMBER' cannot be added to table 'ActInv' because it does not allow nulls and does not specify a DEFAULT definition.

Was it helpful?

Solution

SQL Server 2000 does not check for an empty table. What you are seeing is an improvement in SQL Server 2005/2008.

Either of the following two step processes will make the change in SQL Server 2000 against an empty table:

ALTER TABLE [ActInv] ADD [BATCHNUMBER] NVARCHAR(50) NOT NULL CONSTRAINT ActInv_Temp DEFAULT 'foo'
ALTER TABLE [ActInv] DROP CONSTRAINT ActInv_Temp

go

ALTER TABLE [ActInv] ADD [BATCHNUMBER] NVARCHAR(50) NULL 
ALTER TABLE [ActInv] ALTER COLUMN [BATCHNUMBER] NVARCHAR(50) NOT NULL 

OTHER TIPS

I don't have access to 2000 to verify, but can you add a column with a named default, so that it succeeds, then just drop the named default?

The error message tells you that you cannot add the new column because it does not allow nulls and does not specify a DEFAULT definition.

You need to add a default value to the non-nullable field like this:

ALTER TABLE [ActInv] ADD [BATCHNUMBER] NVARCHAR(50) DEFAULT 'foo' NOT NULL

Edit: I just saw exactly what you do on separate SQL Server installations (2000 and 2005). If the table is truly empty perhaps the best solution is to drop/create the table. It sounds like a bug in SQL Server 2000.

Have you considered the following 2 in sequence:

ALTER TABLE [ActInv] ADD [BATCHNUMBER] NVARCHAR(50) 
GO

ALTER TABLE [ActInv] ALTER COLUMN [BATCHNUMBER] NVARCHAR(50) NOT NULL
GO

I think that should work on 2000 as well (I only have 2005 here)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top