Trying to dynamically change a value in sql

Viewed 27

I am trying to generate a select statement with the hardcoded field in one column but with different values. Is there a better way to do this instead of writing another select statetment since there are different hardcoded values?

    select 
       ppp.category_id,
       ppp.city_id,
       <<hardcoded values>>,
       ppp.address,
       ppp.status
    from product ppp
    where ppp.owner_id = 4186
1 Answers

Expressions in the select-list must be fixed at the time the query is prepared. You can't change that dynamically after the query has been parsed.

If your expression is a constant value, you can inject it as a parameter. Then you can pass the parameter to a prepared statement as you execute the query.

select 
   ppp.category_id,
   ppp.city_id,
   ? as the_third_column,
   ppp.address,
   ppp.status
from product ppp
where ppp.owner_id = 4186

If you have a fixed list of expressions, you could use a CASE statement, and this means it can vary by row, or else by a query parameter:

select 
   ppp.category_id,
   ppp.city_id,
   CASE ppp.fetch_style
    WHEN 1 THEN LOWER(ppp.mycolumn)
    WHEN 2 THEN UPPER(ppp.mycolumn)
    WHEN 3 THEN REVERSE(ppp.mycolumn)
    ELSE ppp.mycolumn
   END AS mycolumn,
   ppp.address,
   ppp.status
from product ppp
where ppp.owner_id = 4186
Related