存储过程自动生成ID Liences作品

    规则存储过程写的很清楚,您应该一看就明白,天天逛园子。感觉大家都在帮助别人我也应该奉献点什么,固展示小作品一个。测试过 至今没发现BUG,当然还有优化空间,您可以自己扩充。

       原理是1张表。存储最后的ID   每次取值在这个判断这个ID 。好处也有很多因为这个ID 是按规则生成的的。所以可以直接拿这个ID 做为参数比如。一个生成的结果。总统计 都可以从ID里直接获得。第一次写。如有不清楚的可以给我留言。Liences@163.com  告别identity(1,1) 。

OK 版 自动生成ID

USE [liences]
GO
/****** 对象:  Table [dbo].[PT_GetID]    脚本日期: 09/26/2011 22:07:49 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[PT_GetID](
    [PTG_ID] [varchar](16) COLLATE Chinese_PRC_CI_AS NOT NULL,
    [PTG_Table] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
    [PTG_PK] [varchar](16) COLLATE Chinese_PRC_CI_AS NULL,
    [PTG_index] [int] NULL,
    [PTG_Time] [datetime] NULL,
    [PTG_Primary] [varchar](16) COLLATE Chinese_PRC_CI_AS NULL,
PRIMARY KEY CLUSTERED
(
    [PTG_ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF

 

 

--存储过程

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go


ALTER proc [dbo].[getID](@table  varchar(20),@key varchar(16))
as
declare @time varchar(16) ---得到当前时间
set @time=(select CONVERT(varchar(12),getdate(),112))

declare @result int  ---判断是否存在(1存在,0不存在)
set @result=(select count(PTG_Table) from PT_GetID where PTG_Table=@table);

declare @new int --是否是新的一天(1是当天 0老数据 )
set @new=(select count(PTG_Table) from PT_GetID where PTG_Table=@table and PTG_Time=@time);


declare @id varchar(36) --getid表中的newid(随即的新ID 只在GETid表中)
declare @newid varchar(36)
set @newid=(select newid())
set @id=(select substring(@newid,1,16))

declare @subkey varchar(16) --
set @subkey=(select substring(@key,1,3)) --   截取过的主键ID 前3位(截取传过来的主键ID)


declare  @primary varchar(16) --新成的主见(变量)
begin

if(0=@result and 0=@new) --空数据
begin
set @primary=(@subkey+@time+'001')
insert into PT_GetID (PTG_ID,PTG_Primary,PTG_Table,PTG_PK,PTG_Time) values(@id,@primary,@table,@key,@time)
end

if(0=@new and 1=@result)--老数据
begin
set @primary=(@subkey+@time+'001')
update PT_GetID  set PTG_Primary=@primary,PTG_Time=@time where PTG_Table=@table
end

if(1=@new and 1=@result)--新数据
begin

declare  @number varchar(16)--(根据转过来的表判断要修改的主键ID,表是唯一的)
set @number=(select PTG_Primary from PT_GetID where PTG_Table=@table)
declare  @max varchar(16)
set @max=(select substring(@number,12,14)+1)  --(Max+1是将要得到ID num的值)

if(1<@max and 10>@max)
begin
set @primary=(@subkey+@time+'00'+@max)
update PT_GetID  set PTG_Primary=@primary where PTG_Table=@table
end
else if(10<@max and 100>@max)
begin
set @primary=(@subkey+@time+'0'+@max)
update PT_GetID  set PTG_Primary=@primary where PTG_Table=@table
end

else
begin
set @primary=(@subkey+@time+@max)
update PT_GetID  set PTG_Primary=@primary where PTG_Table=@table
end

end


end

 

 

 

例子:
exec getID 'BD_BidProjectInfo','BDB_ID'


select * From PT_GetID

 对了。这个不是通用版的。 格式是上面的那种。好处我想大家能明白。

posted @ 2012-02-02 14:13  lieneces  阅读(1374)  评论(0)    收藏  举报