select IDENTITY(int, 1,1) AS ID_Num,* into #temp from 表 select * from #tempselect (select count(*) from 表 where 标识<=tem.标识) rowid,* from 表 tem 这些SQL语句都写得太复杂,看得有点蒙,可以给我讲一些实现原理吧?还有这标识列的值好像是不可以修改的,,,晕
select IDENTITY(int, 1,1) AS ID_Num,* into #temp from 表 select * from #temp这里我看懂了,但可以用select ... into ...并没有实现连续的目的啊,而只是将标识列插入到一个新表中,,,
select (select count(*) from 表 where 标识<=tem.标识) rowid,* from 表 temorselect (select sum(1) from 表 where 标识<=tem.标识) rowid,* from 表 tem --------------rowid 就是你要的连续的记录序号,从1开始至最后一条记录。
标识字段的值不能修改.不连续的时候,可以删除标识字段,再添加上去就行了.例子: alter table 表 drop column 标识字段 alter table 表 add 标识字段 int identity(1,1)
如果你只是想加一个标识字段做为主键的话,可以参考下面的例子,删除后会自动重新排列编号 --自已做标识列的例子:--创建得到最大id的函数 create function f_getid() returns int as begin declare @id int select @id=max(id) from tb set @id=isnull(@id,0)+1 return(@id) end go--创建表 create table tb(id int default dbo.f_getid() primary key,name varchar(10)) go--创建触发器,在删除表中的记录时,自动更新记录的id create trigger t_delete on tb AFTER delete as declare @id int,@mid int select @mid=min(id),@id=@mid-1 from deleted update tb set id=@id,@id=@id+1 where id>@mid go--插入记录测试 insert into tb(name) values('张三') insert into tb(name) values('张四') insert into tb(name) values('张五') insert into tb(name) values('张六') insert into tb(name) values('张七') insert into tb(name) values('张八') insert into tb(name) values('张九') insert into tb(name) values('张十')--显示插入的结果 select * from tb--删除部分记录 delete from tb where name in('张五','张七','张八','张十')--显示删除后的结果 select * from tb--删除环境 drop table tb drop function f_getid
select * from #temp
当然没必要每个表都建,一般只在主键难以确定或主键要用几个字段一起确定时才有必要。
select * from #tempselect (select count(*) from 表 where 标识<=tem.标识) rowid,* from 表 tem
这些SQL语句都写得太复杂,看得有点蒙,可以给我讲一些实现原理吧?还有这标识列的值好像是不可以修改的,,,晕
select * from #temp这里我看懂了,但可以用select ... into ...并没有实现连续的目的啊,而只是将标识列插入到一个新表中,,,
--------------rowid 就是你要的连续的记录序号,从1开始至最后一条记录。
alter table 表 drop column 标识字段
alter table 表 add 标识字段 int identity(1,1)
--自已做标识列的例子:--创建得到最大id的函数
create function f_getid()
returns int
as
begin
declare @id int
select @id=max(id) from tb
set @id=isnull(@id,0)+1
return(@id)
end
go--创建表
create table tb(id int default dbo.f_getid() primary key,name varchar(10))
go--创建触发器,在删除表中的记录时,自动更新记录的id
create trigger t_delete on tb
AFTER delete
as
declare @id int,@mid int
select @mid=min(id),@id=@mid-1 from deleted
update tb set id=@id,@id=@id+1 where id>@mid
go--插入记录测试
insert into tb(name) values('张三')
insert into tb(name) values('张四')
insert into tb(name) values('张五')
insert into tb(name) values('张六')
insert into tb(name) values('张七')
insert into tb(name) values('张八')
insert into tb(name) values('张九')
insert into tb(name) values('张十')--显示插入的结果
select * from tb--删除部分记录
delete from tb where name in('张五','张七','张八','张十')--显示删除后的结果
select * from tb--删除环境
drop table tb
drop function f_getid