Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4184107
  • 博文数量: 240
  • 博客积分: 11504
  • 博客等级: 上将
  • 技术积分: 4277
  • 用 户 组: 普通用户
  • 注册时间: 2006-12-28 14:24
文章分类

全部博文(240)

分类: Mysql/postgreSQL

2007-10-15 14:38:12

1、zerofill把月份中的一位数字比如1,2,3等加前导0

mysql> CREATE TABLE t1 (year YEAR(4), month INT(2) UNSIGNED ZEROFILL,
    -> day INT(2) UNSIGNED ZEROFILL);
Query OK, 0 rows affected (0.11 sec)

mysql> INSERT INTO t1 VALUES(2000,1,1),(2000,1,20),(2000,1,30),(2000,2,2)
    -> (2000,2,23),(2000,2,23);
Query OK, 6 rows affected (0.03 sec)
Records: 6 Duplicates: 0 Warnings: 0

mysql> select * from t1;
+------+-------+------+
| year | month | day |
+------+-------+------+
| 2000 | 01 | 01 |
| 2000 | 01 | 20 |
| 2000 | 01 | 30 |
| 2000 | 02 | 02 |
| 2000 | 02 | 23 |
| 2000 | 02 | 23 |
+------+-------+------+
6 rows in set (0.02 sec)


2、如果有这样的需求:一个字段宽度为6个字符,不足的补零,而且又要自动增加。MYSQL现在好像还没有提供这样的功能,这里我用存储过程来实现。

创建表:
Table   Create Table                                                                          
------  ---------------------------------------------------------------------------------------
lk14    CREATE TABLE `lk14` (                                                                 
          `id` int(6) unsigned zerofill NOT NULL DEFAULT '000000',                            
          `str` char(40) DEFAULT NULL,                                                        
          PRIMARY KEY (`id`)                                                                  
        ) ENGINE=MyISAM DEFAULT CHARSET=gb2312 ROW_FORMAT=DYNAMIC COMMENT='InnoDB free: 0 kB' 


创建SP:

DELIMITER $$

DROP PROCEDURE IF EXISTS `test`.`sp_zerofill`$$

CREATE PROCEDURE `test`.`sp_zerofill`(IN num int)
BEGIN
  declare i int default 1;
  -- initialization value
  set @sqltext = 'insert into lk14 values(0,''char0'')';
  -- begin while
  while i < num do
    set @sqltext = concat(@sqltext,',','(',i,',''char',ceil(num*rand()),''')');
    set i = i + 1;
  end while;
  -- begin dynamic sql
  prepare s1 from @sqltext;
  execute s1;
  deallocate prepare s1;
END$$

DELIMITER ;


调用结果:

call sp_zerofill(6);

select * from lk14 order by id;



query result(6 records)

id str
000000 char0
000001 char2
000002 char2
000003 char2
000004 char3
000005 char5
阅读(4529) | 评论(2) | 转发(0) |
给主人留下些什么吧!~~

yueliangdao06082008-10-21 12:36:41

对于第二种情况,现在提出改正。因为MySQL现在支持这样的ZEROFILL了!

chinaunix网友2008-02-25 00:15:01

太复杂了...