Sql Server batch script to write multiple query results to excel/text files

need to run several Sql Server 2014   select queries and write the results to excel sheets

Example
select docname from TbDocs where plant = 'Plant1'   -   Write to Plant1.xlsx
select docname from TbDocs where plant = 'Plant2'   -   Write to Plant2.xlsx
select docname from TbDocs where plant = 'Plant3'   -   Write to Plant3.xlsx
.. has 20  plants total
I need this Each plant data going to separate excel files , due to some requiremnt
(NOTE:   It can be text files instead of excel files, If I can read it in excel later)
Can I have a batch sql script running and writing it to 20 Plant excel files in one shot?
Sam OZAsked:
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.

Vitor MontalvãoMSSQL Senior EngineerCommented:
You can use the bcp utility.
bcp "select docname from TbDocs where plant = 'Plant1'" queryout "C:\Export\plant1.csv" -S servername -T

Open in new window

If you generate the Plant name inside a loop so you can perform the command to all available plants.

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
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
SQL

From novice to tech pro — start learning today.