create table tt(id int identity(1,1),name varchar(10)) insert into tt values('nn') select * from tt /*id name ----------- ---------- 1 nn */ drop table tt
create table tt(id int identity(1,1),name varchar(10)) insert into tt values('nn') insert into tt values('bb') select * from tt id name ----------- ---------- 1 nn 2 bb drop table tt
建立自增列 identity(int,1,1) 或者查詢生成 --2005 select *, ID=row_number()over(order by (select 1)) from tb --2000 select *, ID=(select count(*) from tb where 主鍵<=t.主鍵) from tb t
不能新创建表啊 我的表是从已有的access中导入的 所以想直接在sqlserver数据库中设置
增加列 alter table tb add id intidentity(1,1)
create table k (id int,b int) insert k select 1,2 union all select 2,3 go --创建一个表结构一样的,目标列为子增列的 create table k1 (id int identity(1,1),b int) --给新表赋值 set identity_insert k1 on insert k1(id,b) select * from k set identity_insert k1 off --删除旧表 drop table k --改名 exec sp_rename 'k1','k' select * from k /* id b ----------- ----------- 1 2 2 3*/
在定义表结构时,指定字段是identity int,1,1 就可以了.
--id = identity(int ,n,m) --自真列, 从n开始,每次加m, id = identity(int,1,1)
id=identity(int,1,1)
insert into tt values('nn')
select * from tt
/*id name
----------- ----------
1 nn
*/
drop table tt
insert into tt values('nn')
insert into tt values('bb')
select * from tt
id name
----------- ----------
1 nn
2 bb
drop table tt
identity(int,1,1)
或者查詢生成
--2005
select *,
ID=row_number()over(order by (select 1))
from tb
--2000
select *,
ID=(select count(*) from tb where 主鍵<=t.主鍵)
from tb t
alter table tb add id intidentity(1,1)
insert k select 1,2
union all select 2,3
go
--创建一个表结构一样的,目标列为子增列的
create table k1 (id int identity(1,1),b int)
--给新表赋值
set identity_insert k1 on
insert k1(id,b)
select * from k
set identity_insert k1 off
--删除旧表
drop table k
--改名
exec sp_rename 'k1','k'
select * from k
/*
id b
----------- -----------
1 2
2 3*/
--id = identity(int ,n,m)
--自真列, 从n开始,每次加m,
id = identity(int,1,1)