问题描述:
单据号生成规则:yyyymmdd(年月日)+ 000001(六位流水号,并且自增),
单据号要求:1.每天从000001开始 2. 单据号要连续啊。
客户端体现:
用户每次打开画面要显示按照上面自动生成的单据号。
疑难点:
多用户操作时画面生成的单据号可能重复啊,这样插入数据库单据号就重复了!
求解决方法??
单据号生成规则:yyyymmdd(年月日)+ 000001(六位流水号,并且自增),
单据号要求:1.每天从000001开始 2. 单据号要连续啊。
客户端体现:
用户每次打开画面要显示按照上面自动生成的单据号。
疑难点:
多用户操作时画面生成的单据号可能重复啊,这样插入数据库单据号就重复了!
求解决方法??
--得到新编号的函数
CREATE FUNCTION f_NextBH()
RETURNS char(8)
AS
BEGIN
RETURN(SELECT 'BH'+RIGHT(1000001+ISNULL(RIGHT(MAX(BH),6),0),6) FROM tb WITH(XLOCK,PAGLOCK))
END
GO--在表中应用函数
CREATE TABLE tb(
BH char(8) PRIMARY KEY DEFAULT dbo.f_NextBH(),
col int)--插入资料
BEGIN TRAN
INSERT tb(col) VALUES(1)
INSERT tb(col) VALUES(2)
INSERT tb(col) VALUES(3)
DELETE tb WHERE col=3
INSERT tb(col) VALUES(4)
INSERT tb(BH,col) VALUES(dbo.f_NextBH(),14)
COMMIT TRAN--显示结果
SELECT * FROM tb
/*--结果
BH col
---------------- -----------
BH000001 1
BH000002 2
BH000003 4
BH000004 14
--*/
得用s lock 你问问大大吧,我也不太清楚
if object_id('num_tb') is not null
drop table num_tb
go
create table num_tb(d datetime,id int)
insert num_tb select getdate(),1
if object_id('tb') is not null
drop table tb
go
create table tb(id varchar(20),name varchar(10)) create clustered index idx_clu_tb on tb(id)
go create trigger tri_tb on tb
INSTEAD OF INSERT
as
begin
set nocount on
declare @i int,@id varchar(20),@j int
select @i=count(*) from inserted
begin tran
update num_tb with(TABLOCKX) set
id=(case when convert(char(8),d,112)=convert(char(8),getdate(),112)
then id+@i else @i end),
@j=(case when convert(char(8),d,112)=convert(char(8),getdate(),112) then id else 0 end),
d=getdate()
commit tran
select * into #t from inserted
update #t set id=convert(varchar(8),getdate(),112)+right('00000'+rtrim(@j),5),@j=@j+1
insert tb select * from #t
end
go
--插入记录测试 insert into tb(name) values('张三')
insert into tb(name) values('李四')
select * from tb
/*
id name
-------------------- ----------
2010012700002 张三
2010012700003 李四
*/
insert into tb select '2010012700003','王五'
/*
id name
-------------------- ----------
2010012700002 张三
2010012700003 李四
2010012700004 王五*/看看这个可以满足吧?
这样实现起业比较容易,也容易解决冲突!