MySQL: Zahl in Datum umwandeln

This blog post has been published on 2012-05-22 and may be out of date.

Falls jemand mal z.B. einen Int-Wert in ein Datum umwandeln muss, kann “CONVERT” bzw. “CAST” weiterhelfen. Auch wenn man eigentlich die Datenbank im Vorhinein so gestalten sollte, dass “date” / “datetime” / … / als Datentyp verwendet wird. ;)

 

Beispiel-Datenbank:

CREATE TABLE `lall` (
`Id` int(11) NOT NULL AUTO_INCREMENT,
`IntDate` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`Id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT INTO `lall` VALUES (1,201001);
INSERT INTO `lall` VALUES (2,201002);
INSERT INTO `lall` VALUES (3,201003);
INSERT INTO `lall` VALUES (4,0);
INSERT INTO `lall` VALUES (5,201011);
INSERT INTO `lall` VALUES (6,201012);
INSERT INTO `lall` VALUES (7,201205);

SQL:

SELECT * FROM lall
WHERE ((CONVERT(CONCAT(IntDate, '01'), datetime))>NOW() - INTERVAL 12 MONTH OR IntDate=0)

< – dieses SELECT-Statement zeigt alle Datensätze an, welche nicht älter als 12 Monate sind oder als (int) Datum “0” eingetragen haben.

CONVERT -> http://dev.mysql.com/doc/refman/5.1/de/charset-convert.html
CONCAT -> http://dev.mysql.com/doc/refman/5.1/de/string-functions.html#id571625
NOW -> http://dev.mysql.com/doc/refman/5.1/de/date-and-time-functions.html#id586485

Published by

voku

Lars Moelleken | Ich bin root, ich darf das!

%d bloggers like this: