日期:2014-05-17  浏览次数:20454 次

数据库自动生成流水编号
问题:
流水编号的要求:
流水编号=当天日期(如:20121014)+号码(如:00001)
其中,号码是自动增长的,每完成一笔业务,也就是往表格中插入一条记录就自动增长1

请问,有MSSQL2008可以实现这个功能吗?
------解决方案--------------------
一张计数表,每天凌晨定时更新为1,然后每次调用后自动加1。
定义一个存储过程,定义一个事务,先从计数表中获取最新计数,然后根据你的规则:

begin transaction

DECLARE @a INT
select @a=col from jishubiao
SELECT CONVERT(VARCHAR(8),GETDATE(),112)+RIGHT('00000'+LTRIM(@a),5)
update jishubiao set col=col+1

commit transaction

确保在一个事务里操作。
------解决方案--------------------

--如果数据是单条插入的,用函数,批量插入的,用 INSTEAD of 触发器
create TRIGGER trg_assign_key ON dbo.SQLText INSTEAD OF INSERT
AS
DECLARE @key AS INT
if @@rowcount = 0 RETURN;
select @key =  isnull(max(SigNo),cast(convert(char(6),getdate(),12)+'000' as int)) 
from SQLText with (xlock,paglock) where SigNo > cast(convert(char(6),getdate(),12)+'000' as int)
INSERT INTO dbo.SQLText(SigNo,[Text],Caption)
  SELECT @key + ROW_NUMBER() OVER(ORDER BY getdate()), [Text],Caption
  FROM inserted
GO