0

It sounds more complicated than it actually is. Here is what I'm trying to do within the SELECT part:

SELECT TIMESTAMPADD(
          UCASE(
                 SUBSTRING(offset_unit,1,CHAR_LENGTH(offset_unit)-1)
                ),1,'2003-01-02') as offset_date

offset_unit is a VARCHAR column in the database. It contains one of the following: "Hours","Minutes".

offset is an INT.

I am trying to convert the offset_unit to uppercase, after I have removed the last character ('s') so I can have a proper interval (MINUTE, HOUR...) so I can get a date that I can use in sorting afterwards, but MySQL keeps throwing an error. I have tested each step by adding one function at a time, and it only fails after I add TIMESTAMPADD. If I enter MINUTE manually then it works.

Any way to get this working?

Additional info: I am running this in CakePHP 1.3, in a find, within the 'fields' array, but that shouldn't be important.

2
  • 1
    What is the MySQL error you get? Why are there backslashes in your query? Commented Aug 23, 2012 at 11:10
  • @Jocelyn just the standard "You have an error in your SQL syntax", nothing helpful. Oops, the backslashes are from the PHP code, editing them out now. Commented Aug 23, 2012 at 11:26

2 Answers 2

3

this can be easily achived by using CASE WHEN clause as:

SELECT (CASE 
            WHEN offset_unit = 'HOURS' 
                   THEN TIMESTAMPADD(HOUR,`offset`,'2003-01-02')
            WHEN offset_unit = 'MINUTES' 
                   THEN TIMESTAMPADD(MINUTE,`offset`,'2003-01-02')
        END) AS offset_date
FROM my_table;

SEE SQLFIDDLE DEMO HERE

Sign up to request clarification or add additional context in comments.

Comments

1

It doesn't work because TIMESTAMPADD does not take a string as the first argument, but a unit keyword, for example MINUTE. My guess is that you need to do this in two steps, first get the unit and then construct a query with the correct keyword.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.