From: stronk7 Date: Thu, 13 Dec 2007 18:02:31 +0000 (+0000) Subject: Added the sql_cast_char2int() funtion to provide cross-db X-Git-Url: http://git.mjollnir.org/gw?a=commitdiff_plain;h=e5e7b2a8feffd4739893107aa6c1b738e23fb920;p=moodle.git Added the sql_cast_char2int() funtion to provide cross-db casting from char/text to integer. MDL-12574 Merged from MOODLE_19_STABLE --- diff --git a/lib/dmllib.php b/lib/dmllib.php index d8e41e60f8..645229022b 100644 --- a/lib/dmllib.php +++ b/lib/dmllib.php @@ -2012,6 +2012,50 @@ function sql_order_by_text($fieldname, $numchars=32) { } } +/** + * Returns the SQL to be used in order to CAST one CHAR column to INTEGER. + * + * Be aware that the CHAR column you're trying to cast contains really + * int values or the RDBMS will throw an error! + * + * @param string fieldname the name of the field to be casted + * @param boolean text to specify if the original column is one TEXT (CLOB) column (true). Defaults to false. + * @return string the piece of SQL code to be used in your statement. + */ +function sql_cast_char2int($fieldname, $text=false) { + + global $CFG; + + $sql = ''; + + switch ($CFG->dbfamily) { + case 'mysql': + $sql = ' CAST(' . $fieldname . ' AS SIGNED) '; + break; + case 'postgres': + $sql = ' CAST(' . $fieldname . ' AS INT) '; + break; + case 'mssql': + if (!$text) { + $sql = ' CAST(' . $fieldname . ' AS INT) '; + } else { + $sql = ' CAST(' . sql_compare_text($fieldname) . ' AS INT) '; + } + break; + case 'oracle': + if (!$text) { + $sql = ' CAST(' . $fieldname . ' AS INT) '; + } else { + $sql = ' CAST(' . sql_compare_text($fieldname) . ' AS INT) '; + } + break; + default: + $sql = ' ' . $fieldname . ' '; + } + + return $sql; +} + /** * Returns the SQL text to be used in order to perform one bitwise AND operation * between 2 integers.