使用MySQL儲存過程實現唯一單號的自增生成

2021-08-21 16:06:37 字數 2909 閱讀 2298

建議先學習mysql的儲存過程

sql語句為

-- ----------------------------

-- table structure for orders

-- ----------------------------

drop table if exists `orders`;

create table `orders` (

`id` int(50) not null auto_increment,

`order_no` int(50) null default null,

`station` varchar(255) character set utf8 collate utf8_general_ci null default null comment '站點名',

primary key (`id`) using btree

) engine = innodb auto_increment = 2 character set = utf8 collate = utf8_general_ci row_format = compact;

-- ----------------------------

-- records of orders

-- ----------------------------

insert into `orders` values (1, 903000001, '903');

create definer=`root`@`localhost` procedure `generate_orderno`(in ordernamepre char(3),out neworderno varchar(9))

begin

declare maxno int default 0 ; -- 定義該站點中當前訂單號最大的號 後六位

declare oldorderno varchar (9) default '' ; -- 定義該站點中的最近的乙個物流單號

select ifnull(order_no, '') into oldorderno -- 取去當前站點的最近的訂單號

from orders

where substring(order_no, 1, 3) = ordernamepre

order by id desc limit 1 ;

if oldorderno != '' then

set maxno = convert(substring(oldorderno,4), decimal) ; -- 如果當前站點有訂單號 則該站點最大號為最近的物流單號的後六位 強轉為數字

end if ;

select concat(ordernamepre, lpad((maxno + 1), 6, '0')) into neworderno ; -- 將站點名902 與生成的物流單號拼接一起 並返回物流單號 其中lpad是左拼接方法 將0拼在物流單號的左邊 拼成6位數

if oldorderno = '' then

insert into orders (order_no, station) values (neworderno, ordernamepre) ; -- 如果當前站點不存在 則插入一條站點記錄

end if ;

update orders set order_no = neworderno where substring(order_no, 1, 3) = ordernamepre; -- 更新當前站點名下的物流單號

}

public void test() ";// 呼叫的sql 

callablestatement cs = con.preparecall(storedproc);

cs.setstring(1, "p1");// 設定輸入引數的值

cs.registeroutparameter(2,oracletypes.varchar);// 註冊輸出引數的型別

return cs;

} }, new callablestatementcallback()

});

}

public void test() ";// 呼叫的sql 

callablestatement cs = con.preparecall(storedproc);

cs.setstring(1, "p1");// 設定輸入引數的值

cs.registeroutparameter(2, oracletypes.cursor);// 註冊輸出引數的型別

return cs;

} }, new callablestatementcallback()

rs.close();

return resultsmap;

} });

for (int i = 0; i < resultlist.size(); i++)

}

MySQL 使用儲存過程實現留存率

delimiter use resourcemanage dev drop procedure if exists stat remain player create definer root localhost procedure stat remain player begin 今天的日期 de...

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

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

Mysql儲存過程使用

案例 create procedure sp insert graduate certificate in psid varchar 200 in certificateid int 32 in number varchar 50 in userid int 32 in starttime date...