SQL流水号生成语句

table
     
        Num        createDate
---------------------------------
      (空)          20090901
      (空)          20090901
      (空)          20090902
      (空)          20090902
      (空)          20090903
      (空)          20090903
---------------------------------
      现在要通过createDate来产生一个流水号(4位) 按当天来生成 换天要重新生成
      即得到结果如下:
table
     
        Num        createDate
---------------------------------
    200909010001    20090901
    200909010002    20090901           
    200909020001    20090902
    200909020002    20090902
    200909030001    20090903
    200909030002    20090903
---------------------------------

 

 

 

create table tb(id int , Num varchar(12),createDate varchar(8))
insert into tb values(1,'','20090901')
insert into tb values(2,'','20090901')
insert into tb values(3,'','20090902')
insert into tb values(4,'','20090902')
insert into tb values(5,'','20090903')
insert into tb values(6,'','20090903')
go

update tb set num = createDate + right('000'+cast((select count(1) from tb where createDate = t.createDate and id < t.id) + 1 as varchar),4) from tb t

select * from tb

drop table tb

/*
id          Num          createDate
----------- ------------ ----------
1           200909010001 20090901
2           200909010002 20090901
3           200909020001 20090902
4           200909020002 20090902
5           200909030001 20090903
6           200909030002 20090903

(所影响的行数为 6 行)

*/

 

declare @tb1 table([createDate] datetime)
insert @tb1
select '20090901' union all
select '20090901' union all
select '20090902' union all
select '20090902' union all
select '20090903' union all
select '20090903'

--SQL 2005
select convert(nvarchar(20),[createDate],112) as  [createDate],convert(nvarchar(20),[createDate],112)+right('0000'+cast(row_number() over (partition by [createDate] order by [createDate]) as nvarchar(10)),4) as num
from @tb1

--SQL2000
select identity(int,1,1) as id,[createDate]
into #tem            
from @tb1

select convert(nvarchar(20),[createDate],112) as  [createDate],convert(nvarchar(20),[createDate],112)+right('0000'+cast((select count(1) from #tem where t.[createDate]=[createDate] and t.id > id)+1 as nvarchar(10)),4) as num
from #tem t

drop table #tem


--测试结果:
/*

createDate           num
-------------------- ------------------------
20090901             200909010001
20090901             200909010002
20090902             200909020001
20090902             200909020002
20090903             200909030001
20090903             200909030002

(6 row(s) affected)

*/

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值