It's certainly a worthy goal:

...to build towards a library of useful and hopefully generic sql statements.
Sadly, SQL doesn't admit genericity easily. SQL isn't a procedural language; that is both its strength and weakness. It doesn't admit variables (not "pure" SQL), so, for example, you can't create a "generic count-duplicates" statement like this:
SELECT @columns, COUNT(*) FROM $table GROUP BY @columns HAVING COUNT(*) > 1
where the above is a mythical SQL-Perl hybrid.

You can get halfway there. In the past, I've often resorted to managing many statements with a bit of Perl. For example, in one of my scripts to rebuild tables you'll find stuff like this:

@key_cols1 = qw(account_id group_id); @key_cols2 = qw(account_id manager_id asset_id); # Later... $set1_sql = 'SELECT ' . join(',', @key_cols1) . 'FROM ' . $table1_name . 'WHERE ' . $table1_cond # You get the idea
So, it's not pretty, but it's better to maintain one set of templates in code than 18 separate SQL files.

You're right, it seems like there should be a better way, but most SQL interpreters seem to stop just a hair short or supporting cool stuff like this. If you can come up with something workable, I'll be the first to grab your stuff!


In reply to Re: How to manage sql statements by VSarkiss
in thread How to manage sql statements by tonyday

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.