SQL Use Column Value as Keyword in Query String

和自甴很熟 提交于 2019-12-13 03:13:32

问题


Ok so here is the example query:

SELECT DISTINCT id, amount FROM tbl_recurring_payment AS t 
WHERE ADDDATE(t.start_date,  INTERVAL (t.period) UPPER(t.unit)) = CURDATE());

The area in question is UPPER(t.unit) where I want that expr to be treated as a mysql keyword (possible values of this column are day, week, month, year). It throws an error since it cant use the expr as a keyword. Is there anything I can do to get this to work or should I just add a check for the unit and hardcode the keyword for each possible value of unit?


回答1:


I really just need to know if its possible to use an column value as a keyword in a query string

NO




回答2:


At first glance, my thought is that I would approach this with a CASE statement:

SELECT    -- Is the DISTINCT really necessary???
    id,
    amount
FROM
    tbl_recurring_payment AS T
WHERE
    CASE t.unit
        WHEN 'YEAR' THEN ADDDATE(t.start_date, INTERVAL t.period YEAR)
        ...
    END = CURDATE()

You might be able to streamline the code a bit (for readability, not performance) by using the INTERVAL syntax without ADDDATE, but I don't use MySQL enough to know if that's possible. (...t.start_date + CASE t.unit WHEN 'YEAR' THEN INTERVAL t.period YEAR...)?



来源:https://stackoverflow.com/questions/6749892/sql-use-column-value-as-keyword-in-query-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!