我有一种情况,如果帐号长度小于11,我需要更新帐号,所以如果不满足,需要用0填充。因此,如果数字是123456,则需要在db中将其更新为00000123456
我为此创建了一个存储过程,并且工作正常,
我需要知道有没有更好的方法来做到这一点?
这是我的SP
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_Update_AccountNumber`()
BEGIN
Drop TABLE IF EXISTS temp_table;
CREATE TEMPORARY TABLE IF NOT EXISTS temp_table (id INT(11),accountnumber varchar(50),
length int,PRIMARY KEY (`id`));
Insert into temp_table(id,accountnumber, length)
select a.id,a.account_number,length(a.account_number) from accounts a
inner join programs p on a.program_id = p.id
where p.abbreviation = 'UA'
and length(a.account_number) < 11;
set @count = (Select count(*) from temp_table);
While @count > 0 Do
set @id = (Select id from temp_table limit 0,1);
set @accountnumber = (Select accountnumber from temp_table limit 0,1);
set @length = (Select length from temp_table limit 0,1);
set @newlength = 11 - @length;
Delete from temp_table where id = @id;
While @newlength > 0 Do
set @accountnumber = concat("0" , @accountnumber);
set @newlength = @newlength - 1;
End While;
Update accounts set account_number = @accountnumber where id = @id;
set @count = (Select count(*) from temp_table);
End While;
END
由于
答案 0 :(得分:1)
在您的数据库中使用zerofill
。当您插入123时,它将生成00000000123。
此处也说明了这一点:http://dev.mysql.com/doc/refman/5.0/en/numeric-type-overview.html
答案 1 :(得分:0)
试试这个
UPDATE accounts
SET account_number = CONCAT(REPEAT('0', 11-LENGTH(account_number)), CONVERT(account_number, CHAR(100)))
WHERE LENGTH(a.account_number) < 11;