我有个字段是自动编号,编号唯一,组成方式是:ABCDE+年份+递增编号,比如ABCDE20148888,但是每到新的一年,比如2015年,递增编号又要从0001开始:ABCDE20150001,这样有什么方法可以实现呢?谢谢!
------解决方案--------------------
create table test(编号 nvarchar(20))
DECLARE @Sequence varchar(4)
SET @Sequence = RIGHT(
(
SELECT MAX(编号)
FROM test
WHERE 编号 LIKE 'ABCDE'+CONVERT (varchar, DatePart(YEAR,GETDATE())) + '%'
),
4
)
IF @Sequence IS NOT NULL
BEGIN
insert test values('ABCDE'+CONVERT (varchar, DatePart(YEAR,GETDATE()))+ right(cast(power(10,4) as varchar)+convert(int,@Sequence)+1,4))
END
ELSE
BEGIN
insert test values('ABCDE'+CONVERT (varchar, DatePart(YEAR,GETDATE()))+'0001')
END
select * from test
/*
ABCDE20140001
ABCDE20140002
ABCDE20140003
*/
getdate() 换成时间就好
------解决方案--------------------
http://blog.csdn.net/roy_88/article/details/1424370
最好用一表来记录,这样效率高
------解决方案--------------------
--建表
create table test(编号 nvarchar(20))
--创建函数 返回0001
set ansi_nulls on
GO
set quoted_identifier on
GO
create function dbo.testcreateid()
returns varchar(15)
as
begin
declare @Sequence varchar(4)
set @Sequence = RIGHT(
(
select MAX(编号)
from test
where 编号 LIKE 'ABCDE'+CONVERT (varchar, DatePart(YEAR,GETDATE())) + '%'
),
4
)
if @Sequence IS NOT NULL
begin
set @Sequence=right(cast(power(10,4) as varchar)+convert(int,@Sequence)+1,4)
end
else
begin
set @Sequence='0001'
end
return @Sequence
end
--获取0001等
declare @num varchar(10)
set @num=dbo.testcreateid()
select @num
/*
0001
*/