SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Get_SY_MaxBH]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Get_SY_MaxBH]
GO


--功能：获得最大编号(无日期)
--著者：李
--exec Get_SY_MaxBH 'LJ','s1',8,'1'
create  PROCEDURE Get_SY_MaxBH
  @BHstr varchar(2),
  @BHType varchar(20),
  @Len   int =3,
  @status varchar(10)='0'
AS
begin 
  if @status='0'
  begin
    IF EXISTS (SELECT * FROM SY_MaxBH WHERE BHstr=@BHstr AND BHType=@BHType And Type='0')
    BEGIN
      UPDATE SY_MaxBH SET BHNo=BHNo+1 WHERE BHstr=@BHstr AND BHType=@BHType And Type='0'
      SELECT MaxBH = rtrim(BHstr) + RIGHT(cast('1'+replicate('0',@Len) as int) + BHNo, @Len) FROM SY_MaxBH  WHERE BHstr=@BHstr AND BHType=@BHType And Type='0'
    END
    ELSE
    BEGIN
      INSERT SY_MaxBH (BHstr, BHType, BHNo,Type) VALUES (@BHstr, @BHType,1,0)
      SELECT MaxBH = rtrim(BHstr) + RIGHT(cast('1'+replicate('0',@Len) as int) + BHNo, @Len) FROM SY_MaxBH  WHERE BHstr=@BHstr AND BHType=@BHType And Type='0'
    END
  end
  else
  begin
    DECLARE @Date DATETIME 
    DECLARE @Datestr CHAR(6)
    SET @Date = GETDATE()
    SET @Datestr = RIGHT(YEAR(@Date) * 10000 + MONTH(@Date) * 100 + DAY(@Date), 6)
    IF EXISTS (SELECT * FROM SY_MaxBH WHERE BHstr=@BHstr AND BHType=@BHType AND BHDate=@Datestr And Type='1')
    BEGIN
	UPDATE SY_MaxBH SET BHNo=BHNo+1 WHERE BHstr=@BHstr AND BHType=@BHType AND BHDate=@Datestr And Type='1'
	SELECT MaxBH = rtrim(BHstr) + BHDate + RIGHT(cast('1'+replicate('0',@Len) as int) + BHNo, @Len) FROM SY_MaxBH  WHERE BHstr=@BHstr AND BHType=@BHType And Type='1'
    END
    ELSE IF EXISTS (SELECT * FROM SY_MaxBH WHERE BHstr=@BHstr AND BHType=@BHType And Type='1')
    BEGIN
	UPDATE SY_MaxBH SET BHDate=@Datestr, BHNo=1 WHERE BHstr=@BHstr AND BHType=@BHType And Type='1'
	SELECT MaxBH = rtrim(BHstr) + BHDate + RIGHT(cast('1'+replicate('0',@Len) as int) + BHNo, @Len) FROM SY_MaxBH  WHERE BHstr=@BHstr AND BHType=@BHType And Type='1'
    END
    ELSE
    BEGIN
	INSERT SY_MaxBH (BHstr, BHType,BHDate, BHNo,type) VALUES (@BHstr, @BHType,@Datestr, 1,1)
	SELECT MaxBH = rtrim(BHstr) + BHDate + RIGHT(cast('1'+replicate('0',@Len) as int) + BHNo, @Len) FROM SY_MaxBH  WHERE BHstr=@BHstr AND BHType=@BHType And Type='1'
    END
  end
end

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

