MySql 運用儲存過程實現主鍵生成

2021-08-26 22:32:31 字數 2700 閱讀 4744

寫了乙個根據當天日期生成序列號主鍵的乙個procedure,規則為:當天的日期加上序列號,如20120604002,表明是2023年06月04號的第2單。

具體的時間方式是通過表的策略來生成的。

生成一張管理表(用於多種主鍵生成)

create table sysoption (

keyname varchar(255),

value varchar(255),

time timestamp

);

然後就是使用儲存過程(結合游標的方式) 來生成主鍵了,如下 :

drop procedure if exists genrecordnum;  

delimiter //

create procedure genrecordnum()

begin

declare rn varchar(255) default null;

declare v_value varchar(255) default null;

declare v_time timestamp default null;

declare hasresult integer default 1;

declare gencursor cursor for select value, time from sysoption where keyname='genrecordnum';

declare continue handler for sqlstate '02000' set hasresult = 0;

open gencursor;

fetch gencursor into v_value, v_time;

close gencursor;

if hasresult=0 then

insert into sysoption values('genrecordnum', '1', now());

set rn = concat(date_format(now(), '%y%m%d'), lpad('1', 3, '0')) ;

else

if date_format(v_time, '%y%m%d')!=date_format(now(), '%y%m%d') then

update sysoption set value='1', time = now();

set rn = concat(date_format(now(), '%y%m%d'), lpad('1', 3, '0')) ;

else

update sysoption set value=1+v_value;

set rn = concat(date_format(now(), '%y%m%d'), lpad(1+v_value, 3, '0')) ;

end if;

end if;

select rn recordnum;

end;//

delimiter ;

儲存過程的理解:

1. 建立游標,用於查詢表中相應的記錄。hasresult表示表中是否有記錄(如果沒有查到記錄,資料庫丟擲「02000」號錯誤,這是設定hasresult為0)

declare gencursor cursor for select value, time from sysoption where keyname='genrecordnum'; 

declare continue handler for sqlstate '02000' set hasresult = 0;

2. 執行資料庫操作,如果沒有記錄,則直接插入資料庫,並返回當前編號,如20120604001;

if hasresult=0 then 

insert into sysoption values('genrecordnum', '1', now());

set rn = concat(date_format(now(), '%y%m%d'), lpad('1', 3, '0')) ;

3. 如果資料庫有記錄,則判斷日期是否為今天,如果不是今天的,則更新時間為今天,並返回今天的第乙個編號,

如20120604001;

if date_format(v_time, '%y%m%d')!=date_format(now(), '%y%m%d') then

update sysoption set value='1', time = now();

set rn = concat(date_format(now(), '%y%m%d'), lpad('1', 3, '0')) ;

4. 如果今天已經有編號生成過了,那直接在原編號的基礎上加1,更新資料庫,然後返回編號,

如20120604002:

else

update sysoption set value=1+v_value;

set rn = concat(date_format(now(), '%y%m%d'), lpad(1+v_value, 3, '0')) ;

下面是使用的結果:

mysql儲存過程寫法 動態引數運用

刪除 drop procedure if exists up common select 建立create procedure up common select in t name varchar 50 begin declare v sql varchar 500 set v sql concat...

mysql儲存登入 MYSQL儲存過程實現使用者登入

create definer root function uc session login re son json,srvjson json returnsjson language sqlnotdeterministiccontainssql sql security definer commen...

MySQL聯合主鍵儲存 mysql聯合主鍵

聯合主鍵就是多個表的主鍵聯合起來作為乙個表的主鍵 這個是摘抄的別人的 create table products description products id int 11 not null,language id int 11 not null default 1 products name v...