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

hi,
i have this system command
sqlcmd -E -i<input file> -o <outputfile>
i want to convert this into using dbi .
if i do a prepare and execute, how can i fetch the outputs sql file contains different type of select/cursor statements.
any help is appreciated
thanks
ak

Replies are listed 'Best First'.
Re: using dbi to run sql file
by mje (Curate) on Feb 03, 2010 at 18:21 UTC

    I have not used sqlcmd but if it is this then you might be able to replicate some of it using DBI and DBD::ODBC. You'll need to prepare and execute your procedures using ODBC syntax "{call proc(?,?,?}" where ? are the parameters and if they use print statements you'll need to use an error handler and odbc_more_results. There are examples in t/20SQLServer.t that comes with DBD::ODBC.

    Without further information that is the best I can do to help at this stage as your question is a little vague.

      thanks for the reply..
      here is the requirement.
      suppose i have following commands in a file (script that generates 'create database user command')
      select * from t1
      selcet * from t2
      update t3 set ..where..
      select * from t4
      they all return different of set of results sets.
      when you have all these selects in a file and using sqlcmd (or isql for syabse etc) you can redirect the output to a file.
      my questions i want to do the similar function using dbi because i don't want to rely on external program inside perl using dbi.
      I am already using dbd::odbc . i was wondering how can fetch record sets if they are different formats.
      pl let me know if you need further information
      thx

        As I said I have no experience of sqlcmd. However I've used DBD::ODBC for ages and know this fairly well. As I've not used sqlcmd I'm not sure what you are expecting as output in the output file. If your input file contains a number of SQL select statements and you want to see result-sets in the output file I'd need to know how you expect the output in the output file. Simplistically I'd say you open a DBI connection to your database, read a line at a time from your input file and feed it into DBI's prepare then execute and lastly (and this is where it is difficult to say) call something like fetchrow_arrayref and Data::Dumper the result into your output file.

        If your problem is that each line in the input file selects a different result-set (i.e., different columns) then you'd need to say how you would like the results to look. Certainly I cannot guess this for you.