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.
LVL 1
LD16Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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;
go

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
LD16Author Commented:
It works, thank you very much!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft DOS

From novice to tech pro — start learning today.