exporting query result to excel - sql-server-2005

I am trying to execute the below sql but I am getting "Invalid object name '.Sheet1$'."
INSERT INTO OPENDATASOURCE
('Microsoft.Jet.OLEDB.4.0',
'Database=c:\test.xls;Extended Properties=Excel 8.0')..[Sheet1$])
SELECT col1 FROM table;
its in mssql 2005.
any help is appreciated.

If you have xp_cmdshell enabled you can do this to export to delimited text file, which will open perfect in Excel.
EXEC xp_cmdshell 'SQLCMD -S [SERVERNAME] -d [DBNAME] -o "C:\Output.txt" -s "," -U "[USERNAME]" -P "[PASWORD]" -Q "SELECT TOP 10 * FROM table"';

According to this posting (and a few other samples Google found for me), you need three dots before the table: 8.0)...[Sheet1$]. (Don't ask me why).
Added: The German translation of this provides a complete example of Excel access:
SELECT * FROM OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0',
'Data Source=C:\DataFolder\Documents\TestExcel.xls;Extended Properties=EXCEL 5.0')...[Sheet1$] ;

Related

SQL Server :query for exporting to file

I'm trying to learn the basics of sql programming, I am working with SQL Server 2014. I have managed to import a file into a table with the command:
BULK INSERT Db.dbo.Co2_table
FROM 'd:\dataset_co2.txt'
with
(
FIRSTROW =2,
ROWTERMINATOR ='\n'
)
GO
I would like to do the dual operation, that is exporting the content of a table to a file. I have tried:
SELECT *
INTO OUTFILE 'C:\datadump\sqldbdump.txt"
FROM dbo.alarms_2_2014
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n';
bcp Db.dbo.Co2_table out "C:\users\ws5.en-cre\desktop\prova.txt" -T –c
sqlcmd -S . -d Db -E -s, -W -Q "SELECT * FROM dbo.Co2_table" > ExcelTest.csv
But none of these seem to work (I get error messages). Any idea?
I suspect you are running those commands from Management Studio. You should use console for this command.This works for me. Also check if you have permissions on that folder.
bcp "select * from Db.dbo.Co2_table" queryout C:\users\ws5.en-cre\desktop\prova.txt -c -T
or
bcp Db.dbo.Co2_table out C:\users\ws5.en-cre\desktop\prova.txt -c -T
Also you have suspicious symbol in c parameter -T –c. It is not a regular dash -.
Thank you for you answers and suggestions, and apologies for my lack of precision and my late reply (in this case I missed the notifications from stackoverflow).
Regarding the question on whether I use mstudio or console, what I do is clicking on “new query” from mstudio, write the code and press execute. So I guess the answer is that I use mstudio.
If I try:
bcp "select * from Db.dbo.Co2_table" queryout
C:\users\ws5.en-cre\desktop\prova.txt -c –T
it says
Msg 102, Level 15, State 1, Line 1 Incorrect syntax near 'queryout'.
I guess in this case one of the problem is that the quotes are missing, but even adding them doesn’t solve the problem.
I am looking for a solution that can be implemented as a script. I am familiar with excel vba macros, I would like to implement something like that.
Thanks,
Alex

sql bcp export error

My query is
EXEC XP_CMDSHELL bcp "select * from dbo.table1" queryout "Z:\test.csv" -T -c -S ".\SQL2012EXPRESS"
I got error saying: Incorrect syntax near 'select * from dbo.table1'.
I wonder what's the problem?
Thanks for advice!
Include the database name as well in your select query like below
bcp "select * from db_name.dbo.table1" queryout "Z:\test.csv" -T -c -S ".\SQL2012EXPRESS"
Also, since you are getting entire table data select * from ... you can just do
bcp db_name.dbo.table1 out "Z:\test.csv" -T -c
EDIT:
I have a DB named test in which have a table named test1. If I try below it complain nothing. Just open a command prompt and run the bcp command
C:\Users\blah>bcp test.dbo.test1 out "D:\test.csv" -T -c
Starting copy...
1 rows copied.
Network packet size (bytes): 4096
Clock Time (ms.) Total : 1 Average : (1000.00 rows per sec.)

bcp utility asking me to enter different parameters i do not undertand

I am using BCP To export data from sqlserver 2008R2 Database Name Health,and a table name patient.The out of the query should be save in a textfile:ApplicantsName.txt located at:
C:\Users\meuser\Desktop ApplicantsName.txt -C -T
After running the following query on the command prompt:
bcp "Select FirstName,LastName,PatientNumber from Health.dbo.Patient order by FirstName" queryout "C:\Users\meuser\Desktop ApplicantsName.txt" -C -T
It prompted me this:
Enter the file storage type of fiedl FirstName [char]:varchar
and then this:
Enter prefix-length of field FirstName[2]:FirstName
I have been entering some values but i think the best is to know how it works.After some time of research on the internet, know using bcp utility is one fastest way to export or import data between instance to a file.I follow exactly the samples provided by MS here but i think i need some practical explanation. Can some guide me how to go about this and a little bit of explanation or relevant ref. will be appreciated too.
#one angry researcher's solution of adding '-C RAW' did not work in my particular case but adding lower-case '-c' did. It performs the operation using a character data type
For instance:
bcp mydb.mytable out c:/temp/data.txt -T -c
You need to add a value for the -C parameter (capital C!). If you do not know what you're using it for, you probably won't be needing it and can omitt it.
Refer to the official documentation: http://msdn.microsoft.com/en-us/library/ms162802.aspx
edit: you could, for example, use
bcp "Select FirstName,LastName,PatientNumber from Health.dbo.Patient order by FirstName" queryout "C:\Users\meuser\Desktop\ApplicantsName.txt" -C RAW -T
You will need to fix your output directory too (seems you forgot a backslash there).
heres the sample bcp command with query and credentials (param)
bcp "SELECT * from yourtable" queryout c:\StockItemTransactionID_c.txt -c -Uusername -Pdbpassword -Sinstance -dYourDBName
Note: -U -P -S are case sensitive.

SQL Server : export query as a .txt file

I am trying to export my SQL Server query results into a folder in .txt format (this is for an automated job)
I know the equivalent in MySQL works with INTO OUTFILE. Does anyone know the best way to do this in SQL Server 2008 Management Studio?
SELECT DISTINCT RTRIM (s1.SGMNTID) AS 'AccCode',RTRIM (s1.DSCRIPTN) AS 'CodeDesc', CASE
WHEN s1.SGMTNUMB = '1' THEN '1'
WHEN s1.SGMTNUMB = '2' THEN '2'
WHEN s1.SGMTNUMB = '3' THEN '110'
WHEN s1.SGMTNUMB = '4' THEN '4'
WHEN s1.SGMTNUMB = '5' THEN '120'
END AS 'AccountType_id',
CASE WHEN s1.SGMTNUMB = '2'
THEN LEFT(s1.SGMNTID, 2)
ELSE 'DEFAULT'
END AS 'AccGroupName'
FROM GL40200 s1
UNION
SELECT REPLACE ([ACTNUMBR_1]+'-'+ [ACTNUMBR_2]+'-'+ [ACTNUMBR_3]+'-'+[ACTNUMBR_4]+'-'+ [ACTNUMBR_5],' ', '') AS 'AccCode',
'' AS 'CodeDesc',
'0' AS 'AccountType_id',
'Default' AS 'AccGroupName'
FROM GL00100 a
INTO OUTFILE 'C:\Users\srahmani\verian/myfilename.txt'
You do this in the SSMS app, not the SQL.
In the toolbar select:
Query --> Results To --> Results To File
Then Execute the SQL statements and it will prompt you to save to a text file with an .rpt extension. Open the results in a Text Editor.
Another way is from command line, using the osql:
OSQL -S SERVERNAME -E -i thequeryfile.sql -o youroutputfile.txt
This can be used from a BAT file and shceduled by a windows user to authenticated.
You can use bcp utility.
To copy the result set from a Transact-SQL statement to a data file,
use the queryout option. The following example copies the result of a query into the Contacts.txt data file. The example assumes that you are using Windows Authentication and have a trusted connection to the server instance on which you are running the bcp command. At the
Windows command prompt, enter:
bcp "<your query here>" queryout Contacts.txt -c -T
You can use BCP by directly calling as operating sytstem command in SQL Agent job.
You can use windows Powershell to execute a query and output it to a text file
Invoke-Sqlcmd -Query "Select * from database" -ServerInstance "Servername\SQL2008" -Database "DbName" > c:\Users\outputFileName.txt
The BCP Utility can also be used in the form of a .bat file, but be cautious of escape sequences (ie quotes "" must be used in conjunction with ) and the appropriate tags.
.bat Example:
C:
bcp "\"YOUR_SERVER\".dbo.Proc" queryout C:\FilePath.txt -T -c -q
-- Add PAUSE here if you'd like to see the completed batch
-q MUST be used in the presence of quotations within the query itself.
BCP can also run Stored Procedures if necessary. Again, be cautious: Temporary Tables must be created prior to execution or else you should consider using Table Variables.
This is quite simple to do and the answer is available in other queries. For those of you who are viewing this:
select entries from my_entries where id='42' INTO OUTFILE 'bishwas.txt';

My bcp hangs after creating an empty file

I am trying to drop a file into a directory on the local machine (same machine running SQL Instance). The content of the table I am trying to drop out is in xml format.
ie. table=xmlOutFiles, fieldName = xmlContent; fieldName contains essentially varchar(max) data that is to become the xml file we need.
When the bcp command is executed it seems to create the file in the #dest location, size = 0 bytes and then the process running from within SMSS just sits there waiting for something!
I cannot do anything with that empty file, like delete it, unless I use task manager to kill the process "bcp.exe".
I have tried multiple combinations of the bcp flags, etc.
Running the bcp command from a system prompt, replacing the "#vars" seems to work but I really need it to be part of my SQL Trigger script and function.
Assistance appreciated!!!!
Select #dest = (Select filename from xmlOutfiles)
Select #cmd = 'bcp "Select xmlContent from ProcureToPay.dbo.XmlOutFiles" queryout '+#dest+' -x -w -T -S' + ##servername
Exec xp_cmdshell #cmd
I have tried executing with -T and -Uusername -Ppassword parameters, etc.
This command works from the DOS prompt:
bcp "Select xmlContent from Procure.To.Pay.dbo.XmlOutFiles" queryout c:\temp\test.xml -x -w -T S<myservernameHere>