SQL生成按月的自动编号

来源:互联网 发布:数据库软件开发 编辑:程序博客网 时间:2024/04/26 19:55
CREATE PROCEDURE [dbo].[Select_NO]
(
   @UserId char(12)
 )
AS
SET NOCOUNT ON
declare @maxNOchar(6),
@newNo int,
@yearMonth char(6),
@resultNo char(12)

--取当前年月YYYYMM
select @yearMonth = convert(nvarchar(6),getdate(),112) --'YYYYMM’

if not exists(select autoid from Orders where convert(nvarchar(6),OrdDate,112) = @yearMonth and UserID = @UserId)
begin
  select @resultNo = @yearMonth + '000001' 
end
else
begin
--取本月最大值
select @maxNO = substring(MAX(ordNO),7,6) from Orders where convert(nvarchar(6),OrdDate,112) = @yearMonth  and UserID = @UserId
--本月最大值加1
select @newno = convert(int,@maxNO) + 1
select @resultNo = @yearMonth + SUBSTRING('000000',1,6-len(@newno)) + CONVERT(varchar(6),@newno)
end


select @resultNo




if @@error > 0 
  return @@error
else
  return -1
0 0
原创粉丝点击