--=============================================
-- Author: <vagerent>
-- Create date: <2006-12-14>
-- Description: <获取编码,形如HEAD20060512000001;(头+日期+6位整数)后面为六位,每新的一年编号重新归0>
-- =============================================
alter PROCEDURE [dbo].[mp_GetPKNo] @sTableName varchar(50), @sFieldName varchar(50),--目标字段 @sHead varchar(50),--前缀,如Head等 @sPK varchar(50) out --输出 AS BEGIN declare @dToday datetime,@sToday varchar(10), @sYear varchar(10),@sSubID varchar(20),@sSql nvarchar(1000);--动态sql一定要用nvarchar!!! set @dToday = getdate(); set @sToday = Convert(varchar,Year(@dToday)) +SubString(Convert(varchar,Month(@dToday)+100),2,2)--加100为了预防03月份前面的0没了,此处103后取第二位开始的两位 +SubString(Convert(varchar,Day(@dToday)+100),2,2); --select @sToday--形如20060512 set @sYear=Convert(varchar(10),Year(getdate())) --select @sYear--形如2006 declare @sHead1 varchar(30),@iHeadLength int; set @sHead1=@sHead+@sYear;--形如HEAD2006 --select @sHead1;--形如HEAD2006 set @iHeadLength=Len(@sHead1);--形如HEAD2006的长度 set @sSql = N'select @sSubID=Max(SubString(' +@sFieldName+','+Convert(varchar(10),@iHeadLength+5)+',6)) from '--000002最大的后六位,避免重复 +@sTableName+' where SubString('+@sFieldName+',1,' +Convert(varchar(10),@iHeadLength)+')='''+@sHead1+''''; --select @sSql;--形如select..先找到有HEAD开头的序列号,然后取出后六位 exec sp_executesql @sSql,N'@sSubID varchar(20) output',@sSubID output; if ((@sSubID='') or (@sSubID is null)) set @sSubID='000001' else begin declare @iSubID int; set @iSubID=Convert(int,@sSubID)+1000001;--前面添加多一位预防0丢失 set @sSubID=SubString(Convert(varchar,@iSubID),2,6)--取出最终想要的000001-999999序列号 end --select @sSubID; set @sPK=@sHead+@sToday+@sSubID; return END