SQL Server 自动生成字符串主键 流水号

--根据给定的编码比如Emp,生成一个字符串类型的流水号,如:20110102Emp0001

--建立表
CREATE TABLE PrimKey(
 cDate datetime not null,
 cChar varchar (3) not null,
 cCount int not null
)

--创建主键的存储过程
Create Proc GetPrimKey
@char varchar(3),
@res nvarchar(15) output
As
Begin

 declare @count int
 begin try
  select @count=isnull(cCount,0) from PrimKey where convert(varchar(8),cDate,112)=Convert(nvarchar(8),getdate(),112) and cChar=@char
  set @count=isnull(@count,0);
  if (@count>0)
  begin
   Update PrimKey set cCount=@count+1 where convert(varchar(8),cDate,112)=Convert(nvarchar(8),getdate(),112) and cChar=@char
  end
  if(@count<=0)
  begin
   Insert into PrimKey values(Convert(nvarchar(10),getdate(),21),@char,1);
  end
  set @res =Convert(nvarchar(8),getdate(),112)+@char+right('00000000'+convert(varchar(5),@count+1),4)
 end try
 begin catch
  set @res='One Error';
 end catch
End

--测试调用

declare @res nvarchar(20)
exec GetPrimKey 'Emp',@res output
print @res

 

 

--Create by Ranen

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值