mysql用預存程序迴圈截取使用者資訊並插入到目標表對應的欄位執行個體

來源:互聯網
上載者:User

作業環境:有表game_list,欄位:uid,score1,score2,seat_id,last_update;
傳入參數為i_player_detail ,傳入的值為多個使用者的id、之前分數、之後分數、座位號,每個使用者的資料用分號(;)隔開;
操作目的:將各個使用者對應的屬性插入到目標表對應的欄位中,last_update為資料更新日期;
傳入參數i_player_detail ,裡面存放多個使用者的資訊,每個使用者的一組資料用分號隔開,每個使用者的資訊多個,比如
“使用者id,score,desk,seat;
使用者id,score,desk,seat;……”

 代碼如下 複製代碼
-- 使用預存程序
delimiter $$

use `log_pdk`$$

drop procedure if exists `game_c`$$

create procedure `game_c` (in i_player_detail varchar(500))
SQL SECURITY INVOKER
BEGIN

DROP TABLE IF EXISTS `temp_list`;

--建立暫存資料表,將截取的資料先插入到暫存資料表
CREATE TEMPORARY TABLE `temp_list`(
`uid` INT(10) UNSIGNED NOT NULL,
`score1` INT(10) UNSIGNED NOT NULL,
`score2` INT(10) UNSIGNED NOT NULL,
`seat_id` TINYINT(3) UNSIGNED NOT NULL
);

-- declare str varchar(500);-- 用來拼接sql動態語句
declare m_detail varchar(500);
declare m_num tinyint;

-- 當傳入的使用者資訊字串中含有分號';',進行截取
set m_num = position(';' in str) -- 不存在分號的時候,返回0
while m_num >= 1 do
begin
set @str = 'insert into temp_list values (' + substring(m_detail,1,m_num-1)+')' -- 截取第一個使用者的資訊(第一個分號前面的字元),插入到暫存資料表
prepare statement1 from @str;
execute statement1;
deallocate prepare statement1;
set m_detail = substring(m_detail,m_num+1); -- 定義除去第一個使用者和分號那部分的字串
set set m_num = position(';' in str);
end while;

-- 從暫存資料表抽出所有欄位,添加時間欄位,插入到表game_list
INSERT INTO `game_list`(`uid`,`score1`,`score2`,`seat_id`, `last_update`)
SELECT `uid`, `score1`, `score2`, `seat_id`, current_date()
FROM `temp_list`;
end$$
delimiter ;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.