See all the problems dynamic SQL causes? :) To remove issues and make it more secure, use a prepared query with placeholders, and supply the value upon execution. Further, if the query will be executed multiple times, a prepared query can run a bit faster, as the optimizer is not usually required after the first run.

Anyway, instead of storing queries in a table, why not just make them views (or stored procedures)? That's what they're for. And, it makes running them a lot easier. If worse comes to worse, you can store the name of the view (or stored procedure) in a table for easy finding. Or, perhaps, the name of the script's internal procedure that executes it.

Side comments on the query itself: The query uses an outer query just to get ids and pass them to the inner query that also has id. Why use two tables? And, order by id desc limit 1 to fetch name can be done via an analytical function. How does this look?:

select distinct foo_id key, last_value(value) over ( partition by foo_id order by id ) value from foo_data where foo_id <> ? and aktivity is true and key = 'name';

Update: Query missed the order by id when fetching name. Here it is again with an analytical function.


In reply to Re: How to interpolate sql-output by chacham
in thread How to interpolate sql-output by Seq

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.