黑暗角落

黑暗角落
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

好久没来了。共享一个自动生成编号的存储过程

Posted on 2006-06-25 22:48  gz.net  阅读(846)  评论(4编辑  收藏  举报

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
ALTER  procedure pGetNewKey
  @cTableName varchar(20) = 'tOrderForm',
  @cKeyField varchar(15) = 'cCode',
  @iKeyLength integer = 12,
  @cResult varchar(15) output
as
  declare @cCode varchar(20),@cMax varchar(20),@cSerial varchar(4), @cSQL varchar(150), @cZero varchar(8)

  create table #a(cMaxCode varchar(10) null)

  if @iKeyLength>10
  begin
    set @cZero=substring('000000000000000',1,@iKeyLength-8)
    set @cSQL=
      'insert into #a select max(substring('+@cKeyField+',9,4)) cMaxCode from '+@cTableName+
      ' where substring('+@cKeyField+',1,8)=convert(char(8),getdate(),112)'
    Exec(@cSQL)

    select @cMax = cMaxCode from #a
   
    if @cMax is null
      set @cMax = '0'

    set @cSerial = convert(varchar(4),convert(int,@cMax)+1)

    set @cCode=convert(char(8),getdate(),112)+stuff(@cZero,@iKeyLength-8+1-len(@cSerial),len(@cSerial),@cSerial)
  end
  else
  begin
    set @cZero=substring('000000000000000',1,@iKeyLength)
    set @cSQL=
      'insert into #a select max('+@cKeyField+') cMaxCode from '+@cTableName

    Exec(@cSQL)

    select @cMax = cMaxCode from #a  

    if @cMax is null
      set @cMax = '0'

    set @cSerial = convert(varchar(4),convert(int,@cMax)+1)

    set @cCode=stuff(@cZero,@iKeyLength+1-len(@cSerial),len(@cSerial),@cSerial)
  end

  set @cResult = @cCode

 

 

 

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO