简体   繁体   English

SQL查询结果到文件脚本

[英]SQL query results to file script

I am running SQL express on a windows 2008 R2 server and trying to write a script to periodically query a database and save the results to a file. 我在Windows 2008 R2服务器上运行SQL Express,并尝试编写脚本来定期查询数据库并将结果保存到文件中。 I have used: 我用过:

sqlcmd -Q SELECT DISTINCT Date from MMD_Scale ORDER BY Date ASC -o testresults.txt

and

bcp "select distinct Date from MMD_Scale ORDER BY Date ASC" queryout testresults.txt -c -T

The problem is that both times it comes back saying the table MMD_Scale cant be resolved. 问题在于,两次都返回表MMD_Scale无法解析。 I have verified the query in the Server management studio. 我已经在服务器管理工​​作室中验证了查询。 There was also some online sources that say to specify the database with -D but when I add it it says -D is obsolete and is ignored. 也有一些在线资源说用-D指定数据库,但是当我添加它时,它说-D已过时且被忽略。 Any help is appreciated. 任何帮助表示赞赏。

The issue is that when sqlcmd or bcp connects, they will connect to your default database. 问题在于,当sqlcmd或bcp连接时,它们将连接到默认数据库。 In this instance, it appears that is not the database that your table resides in. 在这种情况下,似乎不是表所在的数据库。

Try putting "USE [database_name]" in your query. 尝试在查询中放入“ USE [database_name]”。 eg 例如

sqlcmd -Q "USE MyDatabase; SELECT DISTINCT Date from MMD_Scale ORDER BY Date ASC" -o testresults.txt

Or fully-qualify the table name: 或完全限定表名:

sqlcmd -Q "SELECT DISTINCT Date from MyDatabase.dbo.MMD_Scale ORDER BY Date ASC" -o testresults.txt

The -D flag is not the same as -d . -D标志与-d Try sqlcmd -d YourDatabase -Q SELECT DISTINCT Date from MMD_Scale ORDER BY Date ASC -o testresults.txt 尝试sqlcmd -d YourDatabase -Q SELECT DISTINCT Date from MMD_Scale ORDER BY Date ASC -o testresults.txt

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

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