简体   繁体   English

使用Windows批处理脚本将SQL表导出到CSV文件

[英]Exporting SQL Table into a CSV file using Windows Batch Script

I am trying to create a windows batch file to export data from an SQL file to a CSV file. 我正在尝试创建Windows批处理文件,以将数据从SQL文件导出到CSV文件。

I have an SQL file in %MYHOME%\\database\\NET-DB.sql which contains data that is: 我在%MYHOME%\\ database \\ NET-DB.sql中有一个SQL文件,其中包含以下数据:

NET-DB.sql NET数据库

insert into net_network (id, a_id, alias, address, domain, mask) values('NET_10.10.1.0_10', 1, 'Local Network', '10.10.1.0', '', '255.255.252.0');

What I have tried so far in exporting the data from net_network table into a CSV file in my .bat file is with this command: 到目前为止,我尝试使用以下命令将数据从net_network表导出到.bat文件中的CSV文件中:

export.bat export.bat

if not exist "%MYHOME%\net\NUL" mkdir "%MYHOME%\net"
COPY net_network TO '%MYHOME%\net\CSV-EXPORT_FILE.csv' DELIMITER ',' CSV HEADER;
pause

Since that does not work for me, what should be the correct approach for this implementation? 既然这对我不起作用,那么此实现的正确方法应该是什么? Any help will be much appreciated. 任何帮助都感激不尽。

Use SQLCMD 使用SQLCMD

You need to modify the code to make it work in your environment, but here goes. 您需要修改代码以使其在您的环境中工作,但是可以了。

if not exist "%MYHOME%\net\NUL" mkdir "%MYHOME%\net"
cd "C:\your path\to\sqlcmd"
sqlcmd -S YourDBServer -d DB_NAME -E -Q "select id, a_id, alias, address, domain, mask from net_network" 
       -o "CSV-EXPORT-FILE.csv" -s"," -w 255

Some explanations: 一些解释:

-S The database server to connect to. -S要连接的数据库服务器。

-d Name of the database to connect to. -d要连接的数据库的名称。

-Q Query to run, can also be insert, delete, update etc. -Q查询运行,也可以插入,删除,更新等

-o select the output file -o选择输出文件

-s "," separated by comma -s “,”以逗号分隔

-w column width, this has to be as big as your largest columns characters. -w列宽,该宽度必须与最大列字符一样大。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM