-- ==================================================
-- 名称:得到单据流水号
-- 实现功能:取得对应表的计数器,实现流水号功能.
-- 调用示例:SELECT F_LT_GetOrderNo(FId) as FID, * from Tab1 T1
left outer join T_OrderList T2 on T1.FTabID = T2.FID
-- ==================================================
CREATE TABLE T_OrderList(
FID int IDENTITY (1, 1) NOT NULL,
FIncCount int -- 计数器
)
CREATE FUNCTION F_LT_GetOrderNo(@ID int)
AS RETURN VARCHAR(32)
DECLARE @OrderNo int
SELECT @OrderNo = FIncCount FROM T_OrderList WHERE FID = @ID
-- 取得编号后,计数器加1
UPDATE T_OrderList SET FIncCount = FIncCount +1 -- 函数中不允许执行UPDATE,这种情况要怎么处理.
RETURNS @OrderNo
-- 系统单据表,存放系统所以业务单据列表,存有生成流水号计数器
CREATE TABLE T_OrderList(
FID int IDENTITY (1, 1) NOT NULL,
FIncCount int -- 计数器
FOrder varchar(30) not Null
)
-- 系统业务单据,存放企业日常业务数据,具体每单有一个单据流水号
CREATE TABLE T_Order(
FID int IDENTITY (1, 1) NOT NULL,
FNumber varchar(40), -- 单据流水号
FOrderInfo varchar(30)
)
-- 现系统要求自动运算,将运算后的数据填充到T_Order业务表中.填充时各记录要生成不同的单据流水号.我原先的实现想法是用存储过程:
CREATE PROCEDURE P_OnlyC
@CodeC VARCHAR(48) OUTPUT
AS
DECLARE @OnlyC VARCHAR(48)
,@FIncCount INTEGER
-- 取出当前单据流水号
SELECT @FIncCount=FIncCount FROM T_OrderList WHERE FID=@CodeC
-- 流水号加1
SELECT @FIncCount = @FIncCount +1
UPDATE T_OrderList SET FIncCount = @FIncCount WHERE FID= @CodeC
-- 组织各个编码
SELECT @OnlyC = @CodeC + '-' + @OnlyC
SELECT @CodeC = @OnlyC; SELECT @OnlyC AS FNumber
-- print @CodeC
GO
但这程方法不能在SELECT语句运算出的结果中调用.如前面写的SELECT P_OnlyC(FId) as 流水号, * from (select sum(..) from tab..) Tab1 所以我想用函数,但函数里又没办法执行递增流水号:
CREATE FUNCTION F_LT_GetOrderNo(@ID int)
AS RETURN VARCHAR(32)
DECLARE @OrderNo int
SELECT @OrderNo = FIncCount FROM T_OrderList WHERE FID = @ID
-- 取得编号后,计数器加1
UPDATE T_OrderList SET FIncCount = FIncCount +1 -- 函数中不允许执行UPDATE
RETURNS @OrderNo
CREATE PROCEDURE n_GetBillNo
@billType char(2),--单据类型
@BillOutNo nvarchar(50) Output
AS
Begin
declare @NowNO int
declare @date char(10)
declare @Symbol nvarchar(10)
declare @ErrorMsg nvarchar(200)
Set NoCount On
Begin Tran
--设定延时
SET LOCK_TIMEOUT 5000
--取当前序号
Select @NowNO=fnumber,@Symbol=fCode,@date=Convert(char(8),fDate,112) from n_BillNo With(xLock) where fcode=@BillType
if @@Error<>0
begin
Set @ErrorMsg='数据被锁定,请求超时!'
Goto Failed
end
--是否是新的一月
if Convert(char(8),getdate(),112)<>@date
Set @NowNo=1
else
Set @NowNo=@NowNo+1
--更新当前序列号和设置最后更新日期
update n_BillNo set fNumber=@NowNO,fDate=GetDate() where fcode=@BillType
if @@Error<>0
begin
Set @ErrorMsg='更新外部序列号失败!'
Goto Failed
end
--取得单号
Set @BillOutNo=lTrim(@SymBol)+Convert(char(8),GetDate(),112)+Right(('0000'+Convert(varchar,@NowNO)),4)
Goto Succeed
Failed:
RaisError(@ErrorMsg,16,1)
Rollback Tran
Set NoCount Off
Return 1
Succeed:
Commit Tran
Set NoCount Off
Return 0
End
GO