Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 SQL Query Export

Author  Topic 

wsilage
Yak Posting Veteran

82 Posts

Posted - 2014-01-02 : 13:10:22
Is there a way to export query results to an excel fie and add that file as an attachment in the email? All this has to be done using SQL query and it needs to be automated. My coworker tried using Openrowset and BCP, but it is not working.

Any suggestions would be great!

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2014-01-02 : 13:28:37
yes..you can use bcp for exporting query results or use OPENROWSET. Then use sp_send_dbmail and pass filepath value for @attachment parameter to get it attached.
http://www.mssqltips.com/sqlservertip/1202/export-data-from-sql-server-to-excel/



------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

wsilage
Yak Posting Veteran

82 Posts

Posted - 2014-01-02 : 13:45:26
Thanks I tried that this morning and I am getting this error.

output
User name not provided, either use -U to provide the user name or use -T for Trusted Connection
usage: bcp {dbtable | query} {in | out | queryout | format} datafile
[-m maxerrors] [-f formatfile] [-e errfile]
[-F firstrow] [-L lastrow] [-b batchsize]
[-n native type] [-c character type] [-w wide character type]
[-N keep non-text native] [-V file format version] [-q quoted identifier]
[-C code page specifier] [-t field terminator] [-r row terminator]
[-i inputfile] [-o outfile] [-a packetsize]
[-S server name] [-U username] [-P password]
[-T trusted connection] [-v version] [-R regional enable]
[-k keep null values] [-E keep identity values]
[-h "load hints"] [-x generate xml format file]
[-d database name] [-K application intent]
NULL
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2014-01-02 : 13:49:48
the error message is obvious. you need pass either -T as switch if you're using windows authentication or pass sql login username and password using -U and -P switches

see this example where i've dumped result onto a text file

http://visakhm.blogspot.in/2013/10/bcp-out-custom-format-data-to-flat-file.html

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -