We help IT Professionals succeed at work.

Export query into csv with a .sql file

Luis Diaz
Luis Diaz asked
Hello Experts,

I am looking for a sqcmd, bcp, or a VBscript that:

Read a File.sql  which contains a Complex select and queryout  into a csv.

I am aware of the following version:

 sqlcmd -S MyServer -d myDB -E -Q "select col1, col2, col3 from SomeTable"
       -o "MyData.csv" -h-1 -s"," -w 700

However I would like to avoid typing the query in the file I would like to call a File.sql and queryout so I don't know if something like this can work:

 sqlcmd -S MyServer -d myDB -E -Q "File.sql"
       -o "MyData.csv" -h-1 -s"," -w 700

Thank you in advance for your help.
Watch Question

Software Engineer
Instead of -Q use -i:
sqlcmd -S MyServer -d myDB -E -i "File.sql" -o "MyData.csv" -h-1 -s"," -w 700

Open in new window

It's probably a good idea to start your .sql file disabling the row count for example I tested with:
set nocount on;

declare @prod_id int = 2;

select * from products where id = @prod_id;

Open in new window

Luis DiazIT consultant


It works, thank you very much!