(原)用于 SQLServer 自动创建单号的存储过程
场景:
不同的单据根据日期和单据流水自动生成顺序的单号。
解决办法:
if exists(select id from sysobjects where id=object_id('proc_id_builder'))
drop procedure proc_id_builder;
create procedure proc_id_builder(@id char(3))
AS
declare @sn varchar(12)
begin transaction
if not exists(select 1 from t_parameter where c_id = @id)
begin
return -1
end
select @sn = c_value from t_parameter where c_id = @id
if substring(@sn,1,8) > convert(char(8),getdate(),112)
begin
return -1
end
--生成单号
if substring(@sn,1,8) < convert(char(8),getdate(),112)
begin
select @sn = convert(char(8),getdate(),112) + '0001'
end
else
begin
select @sn = convert(char(12),convert(dec,@sn) + 1)
end
--更新单号
update t_parameter
set c_value = @sn
where c_id = @id
if @@error != 0
begin
rollback transaction
return -1
end
commit transaction
select @sn
return;
drop procedure proc_id_builder;
create procedure proc_id_builder(@id char(3))
AS
declare @sn varchar(12)
begin transaction
if not exists(select 1 from t_parameter where c_id = @id)
begin
return -1
end
select @sn = c_value from t_parameter where c_id = @id
if substring(@sn,1,8) > convert(char(8),getdate(),112)
begin
return -1
end
--生成单号
if substring(@sn,1,8) < convert(char(8),getdate(),112)
begin
select @sn = convert(char(8),getdate(),112) + '0001'
end
else
begin
select @sn = convert(char(12),convert(dec,@sn) + 1)
end
--更新单号
update t_parameter
set c_value = @sn
where c_id = @id
if @@error != 0
begin
rollback transaction
return -1
end
commit transaction
select @sn
return;