1

I have created a database, a table, and entries in that table through basic SELECT and INSERT INTO commands.

To view the entries I am using the basic query:

USE test1
SELECT * FROM orders 

where test1 is Database and orders is Table name.

I can see the entries.

How can I store the results to a CSV?

With the query

SELECT * FROM orders
INTO OUTFILE '/path/to/file.csv'
FIELDS ESCAPED BY '""'
TERMINATED BY ',' ENCLOSED BY '"'
LINES TERMINATED BY '\n'" 

I am getting an error

Msg 156, Level 15, State 1, Line 4
Incorrect syntax near the keyword 'INTO'.

7
  • 2
    Welcome to StackOverflow mention your database Commented Aug 19, 2014 at 11:06
  • into should come before clause Commented Aug 19, 2014 at 11:12
  • Judging from the error message, you're using SQL Server - right? There is no INTO OUTFILE ..... command in T-SQL .... Commented Aug 19, 2014 at 11:13
  • yup i am using sql server.. Commented Aug 19, 2014 at 11:47
  • Microsoft SQL Server Management Studio 10.0.1600.22 ((SQL_PreRelease).080709-1414 ) Microsoft Data Access Components (MDAC) 6.1.7600.16385 (win7_rtm.090713-1255) Microsoft MSXML 3.0 4.0 6.0 Microsoft Internet Explorer 9.0.8112.16421 Microsoft .NET Framework 2.0.50727.4984 Operating System 6.1.7600 Commented Aug 19, 2014 at 11:48

2 Answers 2

0

You do have the option to output to csv from within management studio, you can return your grid as normal then right click and click "Save results As..."

or

Using SQLMD as per question How to export SQL Server 2005 query to CSV

sqlcmd -q "select col1,col2,col3 from table" -oc:\myfile.csv -h-1 -s","

Alternative is create it into a variable and then save that via your application e.g.

declare @csv varchar(max) = ""
select @csv += replace(column1, ',','","') + ', ' + replace(column1, ',','","') + char(13) + char(10) from orders
select @csv csv

Regards

Liam

Sign up to request clarification or add additional context in comments.

Comments

-1

If you're not as familiar with SQL and would like a more graphical based approach, you could always use the Import/Export Wizard. Little more user-friendly to people who may be new to SQL.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.