<?xml version="1.0" encoding="windows-1252"?>
<node id="836646" title="Re^2: DBI - Table names &amp; placeholders" created="2010-04-24 02:17:47" updated="2010-04-24 02:17:47">
<type id="11">
note</type>
<author id="483556">
McDarren</author>
<data>
<field name="doctext">
&lt;blockquote&gt;&lt;em&gt;If you're worried about unusual table names&lt;/em&gt;&lt;/blockquote&gt;

Well, no - that's not my problem.&lt;br&gt;
The problem is that I will not know the names of the tables until run-time.&lt;br&gt;

Let me give another (once again, contrived) example, that might explain it a bit better.

&lt;p&gt;Imagine that I have two sets of tables, one a set of transactional records (eg, sales records), and the other a set
of consolidated tables for reporting. So I have a Sales table with attributes for Date/Time, ItemID &amp; Price.

&lt;p&gt;Then I have a set of tables that look like Sales201003, Sales201004, Sales201005, etc - a separate table for each
year/month combination. (This is not the way I would design it - but this is how it is and so I need to deal with it).

&lt;p&gt;The SalesYYYYMM tables have one row per day, per item, along with attributes for the total number sold, and total
revenue.

&lt;p&gt;So I have code that selects records from the Sales table, and then inserts summarised data into the appropriate
SalesYYYYMM tables.

The code I would _like_ to be able to write would look something like this:
&lt;code&gt;
# Some code here which selects data from Sales table
# ...
# ...
# then...

my @sales_inserts;
my $insert_sql = 'INSERT INTO ? (ItemID, Day, Revenue, Count) VALUES (?, ?, ?, ?);
my $sales_insert_dbq = $sales_dbh-&gt;prepare($insert_sql);    
while (my @data = $dbq-&gt;fetchrow_array) { 
    my ($year, $month, $day, $itemid, $revenue, $count) = @data;
    my $sales_table = "Sales$year$month";
    my @insert_values = ($sales_table, $day, $itemid, $revenue, $count);
    push @sales_inserts, [@insert_values];
}       
eval {
    for my $i (0 .. $#sales_inserts) {
        $sales_insert_dbq-&gt;execute(@{$sales_inserts[$i]});
    }                                                   
        $sales_dbh-&gt;commit;
};                                          
if ($@) {
    # Error handling, rollback, etc
}                                   
&lt;/code&gt;                             

But the above won't work because I can't use a placeholder for a table name.&lt;br&gt;
I can work around it easily enough by creating a separate statement handle for each YYYYMM combination.&lt;br&gt;
I'm just not sure what the best approach to that would be.

&lt;p&gt;Oh, and please ignore the fact that it's horrible data base design, and that calculated data is being written back
into the data base. As I said, it's a contrived example that helps to describe my problem.

</field>
<field name="root_node">
836640</field>
<field name="parent_node">
836642</field>
</data>
</node>
