Tuesday, March 21, 2006

MySQL 首字母大写

MySQL 中有个将所有字母大写的函数,UPPER
但是没有将首字母大写的函数,今天要用到,所以写了一个。
mysql > update test set text = concat(upper(left(text, 1)), mid(text, 2, length(text) - 1));

test 是 table 表,text 为表的字段 field

concat 是用来连接字符串的。
upper 是将所有的字母大写
left(text, 1) 是取出 text 的第一个字符
mid(text, 2, length(text) - 1) 是取出从第二个字符到最后一个。

good luck

Update

OK, 这东西对 lin dao 这样的两个字段是不试用,它只能改成 Lin dao. 如果要改为 Lin Dao 的话那就比较复杂了。还好我们可以用 Perl 快速的写一段代码:
#!/usr/bin/perl

use strict;
use DBI;

my $dbh = DBI->connect("DBI:mysql:fayland:localhost",
'root', 'pass', { RaiseError => 1, PrintError => 1 }) or die $DBI::errstr;

my $sth = $dbh->prepare(
qq{SELECT * FROM test}
);
$sth->execute() or die $DBI::errstr;

my $records = $sth->fetchall_arrayref({});

$sth = $dbh->prepare(
qq{UPDATE test SET text = ? WHERE text = ?}
);

foreach my $record (@$records) {
my $old = $record->{text};
$record->{text} =~ s/(\w+)/\u\L$1/g;
$sth->execute($record->{text}, $old) or die $DBI::errstr;
}

print 'ok';

0 Comments:

Post a Comment

<< Home