简体   繁体   English

无法将列添加到现有表

[英]Can not add a column to existing table

I have a table viz. 我有桌子。 expenses with three columns as under 三列的支出如下

ExpenseId int NOT NULL,
ExpenseName varchar(50) NOT NULL,
Invalid bit NOT NULL

To add a new column ( OldCode char(4) not null ), I used design feature for tables in Microsoft SQL Server Management Studio. 要添加新列( OldCode char(4) not null ),我对Microsoft SQL Server Management Studio中的表使用了设计功能。 But I get following error 但我得到以下错误

'Expenses' table “费用”表
- Unable to modify table. -无法修改表格。 Cannot insert the value NULL into column 'OldCode', table 'TransportSystemMaster.dbo.Tmp_Expenses'; 无法将值NULL插入表'TransportSystemMaster.dbo.Tmp_Expenses'的'OldCode'列中; column does not allow nulls. 列不允许为空。 INSERT fails. INSERT失败。 The statement has been terminated. 该语句已终止。

Incidentally I have been able to add same column with same specifications to other tables of the same database. 顺便说一句,我已经能够将具有相同规格的同一列添加到同一数据库的其他表中。

Any help? 有什么帮助吗?

Your Table Consist of Existing Records 您的表由现有记录组成

and you are pushing a new column of type NOT NULL . 并且您正在推送类型为NOT NULL的新列。

so for older records the data have to be something. 因此对于较早的记录,数据必须是某些东西。

try something like this 尝试这样的事情

ALTER TABLE MY_TABLE ADD Column_name INT NULL
GO
UPDATE MY_TABLE <set valid not null values for your column>
GO
ALTER TABLE MY_TABLE ALTER COLUMN Column_name INT NOT NULL
 GO

由于OldCodeNOT NULL ,因此您应该为其指定一个默认值。

当表上有一些行时,您不能添加不可为空的列,您应该为其提供默认值

Alter Table table_name add OldCode int not null DEFAULT(0);

You have to specify values for all the 4 fields of the table, its purely because, while designing the table you set the definition of the columns to be not null. 您必须为表的所有4个字段指定值,这纯粹是因为在设计表时,您将列的定义设置为不为null。 Again you are adding a new column called OldCode and setting to be not null, all ready existing records hasn't got a value. 再次,您将添加一个名为OldCode的新列,并将其设置为非null,所有就绪的现有记录都没有值。 So that is the reason its complains 所以这就是它抱怨的原因

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM