Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a sql script file using sqlcmd and output to both shell and file

Tags:

logging

sqlcmd

I'm trying to run a sql script from a file using sqlcmd, using the following command:

sqlcmd -S <server> -d <database> -i <input file> -o <output file> 
      -U <user> -P <password>

I run my sql file and output to a log file.

The problem is this change the output of sqlcmd to the file.. and i want to get the output also to the shell.

like image 528
Noam Shaish Avatar asked Feb 06 '12 18:02

Noam Shaish


People also ask

How do I run a script using SQLCMD?

You can run sqlcmd as commands. You can run scripts in command mode. In the next example, we will show how to run a script using sqlcmd and show the results in another file. We will first create a script file named columns.sql with the following sentences:

Is it possible to run a script in SQL?

Yes, the script works suscefull, it's not an issue question. And yes, I've a "print "something" on my sql. The log file gets the output. Thanks a lot! Similar question without answer: How to run a sql script file using sqlcmd and output to both shell and file

How to use batch files in SQLCMD?

The batch files simply accept a list of arguments from cmd prompt and allow the program to function based on the order of input parameter -S ->This option can be used to specify to which SQL Server Database Engine instance SQLCMD should connect.

How do I run a SQL query in CMD?

In the cmd, run the following command to invoke sqlcmd: sqlcmd -S DESKTOP-5K4TURFSQLEXPRESS -E -i c:sqlcolumns.sql -o c:sqlexit.txt. -i is used to specify the input. You specify the script file with the queries. -o is used to show the results of the input in a file.


1 Answers

@Noam, albeit I couldn't find a way of duplicating the STDOUT handler, one solution that maybe solve you problem is to execute the sql script into the output file (i.e. result.txt) and then use type result.txt to print it into STDOUT.

c:>sqlcmd -i mysrcipt.sql -o result.txt -S myserver -E
c:>type result.txt

If you really need to duplicate the handler (maybe the command takes lots of time and you don't want to wait until it finishes before getting the first rows), you can make a simple program to copy the inputs from STDIN into STDOUT and also into a file. Then you could rewrite the command as:

c:>sqlcmd -i mysrcipt.sql -S myserver -E > duplicate.exe "result.txt"
like image 176
Gerardo Lima Avatar answered Oct 19 '22 08:10

Gerardo Lima