相关资讯
本类常用软件
-
福建农村信用社手机银行客户端下载下载量:584204
-
Windows优化大师下载量:416898
-
90美女秀(视频聊天软件)下载量:366961
-
广西农村信用社手机银行客户端下载下载量:365699
-
快播手机版下载量:325855
ALTER TABLE 只允许添加可包含空值或指定了 DEFAULT 定义的列。
如果:
IF EXISTS(SELECT 1 FROM SYSOBJECTS WHERE NAME = N'tab_test') AND NOT EXISTS(SELECT 1 FROM SYSOBJECTS A, SYSCOLUMNS B WHERE B.ID = A.ID AND B.NAME = N'col_test' and a.name = N'tab_test')
alter table tab_test
add col_test smallint NOT NULL
GO
将会收到错误信息。
要增加非空列怎么办呢?
第1种办法:在add column时指定列有default
alter table tab_test
add col_test NOT NULL CONSTRAINT DFtab_test_col_test DEFAULT 1
第2种办法:先给表增加个table_constraint default,再alter column
alter table tab_test
add CONSTRAINT DFtab_test_col_test DEFAULT 1 for col_testalter table tab_test
alter column col_test int NOT NULL
第3种办法:只好先增加空列,在修改为非空啦:
IF EXISTS(SELECT 1 FROM SYSOBJECTS WHERE NAME = N'tab_test') AND NOT EXISTS(SELECT 1 FROM SYSOBJECTS A, SYSCOLUMNS B WHERE B.ID = A.ID AND B.NAME = N'col_test' and a.name = N'tab_test')
alter table tab_test
add col_test smallint
GO
alter table tab_test
alter column col_test smallint not null
GO
语法如下:
ALTER TABLE table_name ALTER COLUMN column_name { type_name[({precision[.scale]})][NULL|NOT NULL] {DROP DEFAULT | SET DEFAULT constant_expression | IDENTITY [ ( seed , increment ) ] } | ADD { < column_definition > | < table_constraint > } [ ,...n ] | DROP { [ CONSTRAINT ] constraint_name | COLUMN column } ] } < column_definition > ::= { column_name data_type } [ [ DEFAULT constant_expression ] | IDENTITY [ ( seed , increment ) ] ] [ROWGUIDCOL] [ < column_constraint > ] [ ...n ] ] < column_constraint > ::= [ NULL | NOT NULL ] [ CONSTRAINT constraint_name ] { | { PRIMARY KEY | UNIQUE } | REFERENCES ref_table [ (ref_column) ] [ ON DELETE { CASCADE | NO ACTION | SET DEFAULT |SET NULL } ] [ ON UPDATE { CASCADE | NO ACTION | SET DEFAULT |SET NULL } ] } < table_constraint > ::= [ CONSTRAINT constraint_name ] { [ { PRIMARY KEY | UNIQUE } { ( column [ ,...n ] ) } | FOREIGN KEY ( column [ ,...n ] ) REFERENCES ref_table [ (ref_column [ ,...n ] ) ] [ ON DELETE { CASCADE | NO ACTION | SET DEFAULT |SET NULL } ] [ ON UPDATE { CASCADE | NO ACTION | SET DEFAULT |SET NULL } ] }