请问我怎么SELECT出来一个流水号呢?从1开始,每一条+1,表里没有这个字段,要在SQL里生成,有办法吗?

jerry_huang 2003-12-23 04:55:15
谢谢!
...全文
112 10 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
qjt 2003-12-23
  • 打赏
  • 举报
回复
用游标可以实现
declare @temp varchar(10)
declare @i int
declare cur_test cursor
for
select column_name from tablename
open cur_test
set @i=0
fetch next from cur_test into @temp
while @@fetch_status=0
begin
set @i=@i+1
print CONVERT(varchar(30), @i)+' '+@temp
fetch next from cur_test into @temp
end

close cur_test
deallocate cur_test

结果如下
1 admin
2 swufe
3 lyh
muge 2003-12-23
  • 打赏
  • 举报
回复
alter table 你的表名 add 增加的字段 int IDENTITY
hmzgz81 2003-12-23
  • 打赏
  • 举报
回复
呵呵,不就是在前面加个序列吗!!!

identity(int,1,1)
fanmb 2003-12-23
  • 打赏
  • 举报
回复
viptiger(六嘎) 和 devilwind(天空星) 的已經夠高效了
xiaoBrother 2003-12-23
  • 打赏
  • 举报
回复
有更简单且高效率的方法吗?
gmlxf 2003-12-23
  • 打赏
  • 举报
回复
如果你的table里面有唯一字段,或者是组合唯一字段.

现在比如t里面有一Sn字段是唯一的,那么
select (select count(*) from t where Sn<=a.Sn) 流水号,* from t a order by Sn

如果Sn1,Sn2构成唯一,那么
select (select count(*) from t where Sn1<=a.Sn1 and Sn2<=a.Sn2) 流水号,* from t a order by Sn1,Sn2


solidpanther 2003-12-23
  • 打赏
  • 举报
回复
--自已做标识列的例子:

--创建得到最大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(),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
viptiger 2003-12-23
  • 打赏
  • 举报
回复
alter table YouTable add col int IDENTITY
victorycyz 2003-12-23
  • 打赏
  • 举报
回复
select *,identity(int,1,1) as id into #t from Tablename
select * from #t
drop table #t
devilwind 2003-12-23
  • 打赏
  • 举报
回复
IDENTITY(函数)
只用在带有 INTO table 子句的 SELECT 语句中,以将标识列插入到新表中。

尽管类似,但是 IDENTITY 函数不是与 CREATE TABLE 和 ALTER TABLE 一起使用的 IDENTITY 属性。

语法
IDENTITY ( data_type [ , seed , increment ] ) AS column_name

34,838

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧