SQL Server 自动生成字符串主键 流水号
2011-05-10 08:40
393 查看
--根据给定的编码比如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
--建立表
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
@res
--Create by Ranen
相关文章推荐
- SQL Server 自动 生成流水号 字符串主键
- iBatis自动生成的主键 返回主键 (Oracle,Sql Server,Mysql,SQLite)
- SQL SERVER 根据日期自动生成流水号
- SQL Server主键自动生成_表and存储过程
- SQL Server 生成带流水号的字符串
- iBatis自动生成的主键 返回主键 (Oracle,Sql Server,Mysql)
- iBatis自动生成的主键 返回主键 (Oracle,Sql Server,Mysql) 转自:http://www.oraforum.net/thread-421-1-1.html
- SQL 流水号 字符串主键
- sqlserver2000字段自动生成流水号
- C#自动生成流水号怎么写
- Hibernate保存数据自动生成主键出现奇怪异常Duplicate entry '0' for key 1
- 生成索引信息及自动创建脚本(Sql Server 2000)
- SQL Server自动生成INSERT语句
- 【Ibatis】(七)、自动生成主键
- Java根据字符串生成固定长度的流水号
- Hibernate知识清单1--Hibernate 中oracle 主键的自动生成办法
- iBatis自动生成的主键 (Oracle,MS Sql Server,MySQL)
- 主键自动生成办法
- MyBatis 3 自动生成 主键 针对不同的数据库(oracle/sqlserver/mysql)
- 自动生成业务单据流水号方案