public function formattedDatetimeClause($date, $format)
    {
        preg_match_all('/%(.)/', $format, $matches);
        foreach ($matches[1] as $match) {
            if (array_search($match, array('Y', 'm', 'd', 'H', 'i', 's', 'U')) === false) {
                user_error('formattedDatetimeClause(): unsupported format character %' . $match, E_USER_WARNING);
            }
        }

        if (preg_match('/^now$/i', $date)) {
            $date = "CURRENT_TIMESTAMP";
        } elseif (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/i', $date)) {
            $date = "'$date.000'";
        }

        if ($format == '%U') {
            return "DATEDIFF(s, '1970-01-01 00:00:00', DATEADD(hour, DATEDIFF(hour, GETDATE(), GETUTCDATE()), $date))";
        }

        $trans = array(
            'Y' => 'yy',
            'm' => 'mm',
            'd' => 'dd',
            'H' => 'hh',
            'i' => 'mi',
            's' => 'ss',
        );

        $strings = array();
        $buffer = $format;
        while (strlen($buffer)) {
            if (substr($buffer, 0, 1) == '%') {
                $f = substr($buffer, 1, 1);
                $flen = $f == 'Y' ? 4 : 2;
                $strings[] = "RIGHT('0' + CAST(DATEPART({$trans[$f]},$date) AS VARCHAR), $flen)";
                $buffer = substr($buffer, 2);
            } else {
                $pos = strpos($buffer, '%');
                if ($pos === false) {
                    $strings[] = $buffer;
                    $buffer = '';
                } else {
                    $strings[] = "'".substr($buffer, 0, $pos)."'";
                    $buffer = substr($buffer, $pos);
                }
            }
        }

        return '(' . implode(' + ', $strings) . ')';
    }