如何在sql中添加流水号列

熊猫哥 2004-04-06 10:47:56
如题
...全文
261 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
熊猫哥 2004-04-06
  • 打赏
  • 举报
回复
我的问题时用SELECT * FROM TABLE时在前面增加一个从1~n的标识列
不能在数据库中增加表,也不能使用视图、函数和存储过程
myperry 2004-04-06
  • 打赏
  • 举报
回复
table1 有2个字段,内容如下:
aaa, bbb
a1 b7
a0 b2
a4 b9
......


要得出如下结果:
no_id, aaa, bbb
1 a1 b7
2 a0 b2
3 a4 b9
......

--如果aaa+bbb的组合不重复,可以用:

select no_id=(select sum(1) from table1 where aaa<=a.aaa and bbb<=a.bbb) ,aaa,bbb
from table1 a
order by aaa,bbb

--如果这些条件都不满足,就用临时表
select IDENTITY(int,1,1) as no_id, aaa, bbb into #tmp from table1
select * from #tmp order by no_id
drop table #tmp


progress99 2004-04-06
  • 打赏
  • 举报
回复
--自已做标识列的例子--流水号:日期+当日编号:
zjcxc

--创建得到最大id的函数
create function f_getid()
returns varchar(12)
as
begin
declare @id varchar(12),@dt varchar(8)
select @dt=dt from v_getdate
select @id=max(id) from tb where id like @dt+'-%'
if @id is null
set @id=@dt+'-'+'001'
else
set @id=@dt+'-'+right('000'+cast(cast(right(@id,3) as int)+1 as varchar),3)
return(@id)
end
go

--创建表
create table tb(id varchar(20) default dbo.f_getid() primary key,name varchar(10))
go

--创建视图,得到当前日期(因为函数中不能使用getdate())
create view v_getdate as select dt=convert(varchar,getdate(),112)
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
go
--删除环境
drop table tb
drop view v_getdate
drop function f_getid
progress99 2004-04-06
  • 打赏
  • 举报
回复
設一identity字段,插入記錄時此字段自己產生遞增值。

34,838

社区成员

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

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