developer has asked for the wisdom of the Perl Monks concerning the following question:

Hi: I am using WIN32::ODBC to get the column names of multiple tables. I am able to get the column name and length, I also need the table name. The join tables have some columns of the same name. Can some one please help. my code looks like this : my(@fields) = $db->FieldNames; to get columns, how to I get the the column name with table names. thanks

Replies are listed 'Best First'.
Re: Table name and COLUMN Names
by Enlil (Parson) on Jul 30, 2004 at 00:55 UTC
    how to I get the the column name with table names. thanks

    Something like this might help:

    #!/usr/bin/perl use strict; use warnings; use Win32::ODBC; my $db = new Win32::ODBC("DSN") or die Win32::ODBC::Error(); my @table_list = $db->TableList(); my %tables; for my $table ( @table_list ) { if ( $db->Sql("Select * from $table") ) { print "Error: " . $db->Error() . "\n"; $db->close(); exit; } else { @{$tables{$table}} = $db->FieldNames(); } } $db->Close(); foreach my $table ( keys %tables ) { print "TABLE $table CONTAINS:\n"; foreach my $column ( @{$tables{$table}} ) { print "\t$column\n"; } }
    You've mentioned you already know how to get the length. Another method you might want to look at is DBD::ODBC using DBI which might make some things easier (I prefer it to Win32::ODBC) anyhow here is some code using DBI to get the information you ask:
    #!/usr/bin/perl use strict; use warnings; use DBI; my $dbh = DBI->connect("dbi:ODBC:table","name","password") or die $DBI::errstr; my $sth_t = $dbh->table_info(); my @tables; while (my $table = ($sth_t->fetchrow())[2] ) { #Comment out next line if MSys* tables wanted #which might just be an Access thing anyhow next if $table =~ /^MSys/; push @tables,$table; } printf "%20s %20s %20s\n", 'TABLE','COLUMN NAME', 'COLUMN SIZE'; foreach my $table ( @tables ) { my $sth_c = $dbh->column_info( undef, undef, $table, undef ); while ( my ($table_name,$column_name, $column_size ) = ($sth_c->fetchrow())[2,3,6] ) { printf "%20s %20s %20s\n", $table_name, $column_name, $column_size; } } $dbh->disconnect();

    -enlil

Re: Table name and COLUMN Names
by McMahon (Chaplain) on Jul 29, 2004 at 22:36 UTC
    Hello...
    You want something like (untested and probably incomplete, but it'll get you started...):
    my $sth1 = $dbh->table_info(); while (my(@tab) = $sth1->fetchrow_array()) { push @colNames, $tab[2]; } ... my $sth2 = $dbh->column_info() while (my @info = $sth->fetchrow_array()) { if ($colName eq $info[2]) { print OUT "\t$info[3]\n"; } #END IF }#END WHILE
Re: Table name and COLUMN Names
by developer (Novice) on Aug 04, 2004 at 14:48 UTC
    Thanks for the reply. Here is the problem I have. I am doing a select * from a.table1, b.table2. When I am getting the field names I also need to know from which table is this column from. Some column names are identical. I hope I have explained my requirements. Thanks