Export query into csv with a .sql file

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.
Who is Participating?
Robert SchuttSoftware EngineerCommented:
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

LD16Author Commented:
It works, thank you very much!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.