怎么自动生成我想要的格式流水号
格式:字母+时间+流水+编号
列如流水号:CD201308310001
CD201308310002
CD201308310003
CD201308310004
这种格式流水号在数据库怎么形成??
[解决办法]
select top 20 'CD'+replace(convert(varchar(10),getdate(),120),'-','')+right('0000'+cast(number as varchar),5) as code
from master..spt_values
where type='P' and number>0
结果:
/*
CD2013083100001
CD2013083100002
CD2013083100003
CD2013083100004
CD2013083100005
CD2013083100006
CD2013083100007
CD2013083100008
CD2013083100009
CD2013083100010
CD2013083100011
CD2013083100012
CD2013083100013
CD2013083100014
CD2013083100015
CD2013083100016
CD2013083100017
CD2013083100018
CD2013083100019
CD2013083100020
*/
select top 20 'CD'+replace(convert(varchar(10),getdate(),120),'-','')+right('000'+cast(number as varchar),4) as code
from master..spt_values
where type='P' and number>0
/*
CD201308310001
CD201308310002
CD201308310003
CD201308310004
CD201308310005
CD201308310006
CD201308310007
CD201308310008
CD201308310009
CD201308310010
CD201308310011
CD201308310012
CD201308310013
CD201308310014
CD201308310015
CD201308310016
CD201308310017
CD201308310018
CD201308310019
CD201308310020
*/
DECLARE @length INT, @count INT
SET @length = 4--指定序列号长度
SET @count = 1000--指定要生成的序列号个数
;WITH
cte1 AS (SELECT number = 1 UNION ALL SELECT 1),
cte2 AS (SELECT number = 1 FROM cte1 a CROSS JOIN cte1 b),
cte3 AS (SELECT number = 1 FROM cte2 a CROSS JOIN cte2 b),
cte4 AS (SELECT number = 1 FROM cte3 a CROSS JOIN cte3 b),
cte5 AS (SELECT number = 1 FROM cte4 a CROSS JOIN cte4 b),
cte6 AS (SELECT number = 1 FROM cte5 a CROSS JOIN cte5 b)
SELECT TOP(@count) num =
'CD'+ CONVERT(CHAR(8),GETDATE(),112)+
RIGHT(REPLICATE('0', @length) + LTRIM(ROW_NUMBER() OVER(ORDER BY GETDATE())), @length)
FROM cte6
/*
num
CD201308310001
CD201308310002
CD201308310003
*/
--1. 建表
create table tb(itemNo varchar(20))
--2. 建个存储过程最流水号
create proc GetMaxNo @itemNo varchar(20) output
as
set nocount on
declare @maxNo varchar(20),@i int
set @maxNo='CD'+replace(convert(varchar(10),getdate(),120),'-','')
select @i=isnull(max(right(itemNo,4)),0)+1 from tb where itemNo like @maxNo+'%'
set @maxNo=@maxNo+right('000'+cast(@i as varchar),4)
set @itemNo=@maxNo
return
go
--新增时调用
declare @itemNo varchar(20)
exec GetMaxNo @itemNo output
insert into tb(itemNo) values(@itemNo)
--测试,新增四次结果
select * from tb
/*
CD201308310001
CD201308310002
CD201308310003
CD201308310004
*/