SQL Server中应当怎样得到自动编号字段
作者:68310 时间:2009-01-15 12:48:00
问题:SQL Server 2000中设计表时如何得到自动编号字段?
解答:具体步骤如下:
①像Access中的自动编号字段
右键你的表-->设计表-->找到你的id字段(类int型)-->标识-->是-->标识种子(初始值)-->标识递增量-->OK
②用IDENTITY (SEED,INCREMENT)参数
seed -启始值
increment -增量
CREATE TABLE 表名(
你的ID IDENTITY (1, 1) NOT NULL ,你的其他字段... )
CREATE TABLE 表名(
你的字段ID AUTOINCREMENT(1000,10),其他字段... )
③修改起始值和步进值
ALTER TABLE 表名 ALTER COLUMN 你的字段ID COUNTER(2000,50)
④让一个删空的表自动增加字段的开始值重新从1开始
ALTER TABLE 表名 ALTER COLUMN 你的字段ID COUNTER(1,1)
上述3 4只适用与Access,COUNTER为其一种数据类型,可以在Access中指定一不是自动编号的字段为自动编号字段,也可以让一自动编号字段重新从指定值按指定步长自动编号。但是如果表中有数据,用户不能用该语句来将该列的数据类型改变为COUNTER 数据类型。对于SQL Server并不支持。
对于SQL Server我们或许总希望用Alter Table 表名 Alter Column 你的字段 IDENTITY(1,1)
来指定字段重新从1开始计数,但是这句话本身是错误的,好长时间我也疑惑为什么这句话不能执行。如果我们看看MS 对Alter Table语句的定义就清楚了,这句话根本是错误的。下面是MS对Alter Table语句的定义。
ALTER TABLE table
{ [ ALTER COLUMN column_name
{ new_data_type [ ( precision [ , scale ] ) ]
[ COLLATE < collation_name > ]
[ NULL | NOT NULL ]
| {ADD | DROP } ROWGUIDCOL }
]
| ADD
{ [ < column_definition > ]
| column_name AS computed_column_expression
} [ ,...n ]
| [ WITH CHECK | WITH NOCHECK ] ADD
{ < table_constraint > } [ ,...n ]
| DROP
{ [ CONSTRAINT ] constraint_name
| COLUMN column } [ ,...n ]
| { CHECK | NOCHECK } CONSTRAINT
{ ALL | constraint_name [ ,...n ] }
| { ENABLE | DISABLE } TRIGGER
{ ALL | trigger_name [ ,...n ] }
}
< column_definition > ::=
{ column_name data_type }
[ [ DEFAULT constant_expression ] [ WITH VALUES ]
| [ IDENTITY [ ( seed , increment ) [ NOT FOR REPLICATION ] ] ]
]
[ ROWGUIDCOL ]
[ COLLATE < collation_name > ]
[ < column_constraint > ] [ ...n ]
< column_constraint > ::=
[ CONSTRAINT constraint_name ]
{ [ NULL | NOT NULL ]
| [ { PRIMARY KEY | UNIQUE }
[ CLUSTERED | NONCLUSTERED ]
[ WITH FILLFACTOR = fillfactor ]
[ ON { filegroup | DEFAULT } ]
]
| [ [ FOREIGN KEY ]
REFERENCES ref_table [ ( ref_column ) ]
[ ON DELETE { CASCADE | NO ACTION } ]
[ ON UPDATE { CASCADE | NO ACTION } ]
[ NOT FOR REPLICATION ]
]
| CHECK [ NOT FOR REPLICATION ]
( logical_expression )
}
< table_constraint > ::=
[ CONSTRAINT constraint_name ]
{ [ { PRIMARY KEY | UNIQUE }
[ CLUSTERED | NONCLUSTERED ]
{ ( column [ ,...n ] ) }
[ WITH FILLFACTOR = fillfactor ]
[ ON { filegroup | DEFAULT } ]
]
| FOREIGN KEY
[ ( column [ ,...n ] ) ]
REFERENCES ref_table [ ( ref_column [ ,...n ] ) ]
[ ON DELETE { CASCADE | NO ACTION } ]
[ ON UPDATE { CASCADE | NO ACTION } ]
[ NOT FOR REPLICATION ]
| DEFAULT constant_expression
[ FOR column ] [ WITH VALUES ]
| CHECK [ NOT FOR REPLICATION ]
( search_conditions )
}