Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
572 views
in Technique[技术] by (71.8m points)

need help to export table from sql server 2008 to text file

I am trying to export a table present in ms sql server 2008 to a text file on my system. I am writing the following command in sql server query window

SELECT *
FROM [AdventureWorks].[Person].[AddressType] 
INTO OUTFILE 'C:/filename.csv'
FIELDS TERMINATED BY ','
LINES TERMINATED BY '
';

Now whenever I write this command the sql help gives me error that incorrect syntax near 'INTO'

then I tried interchanging from and into keywords as follows

SELECT *
INTO OUTFILE 'C:/filename.csv'
FIELDS TERMINATED BY ','
LINES TERMINATED BY '
'
FROM [AdventureWorks].[Person].[AddressType] ;

Now it gives me error that incorrect syntax near 'C:/filename.csv'

Please help me regarding this. I am not able to remove these error and get a working sql

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are more than many ways to solve a problem , In this case here are two solutions

Solution 1

  • Right Click over the Database name -> Tasks -> Export Data
  • Choose the table as Data Source
  • Choose Flat file destination as destination
  • Choose a File-name ( any file name )
  • Mark "Column Names in the first data row" ( this is opitional)

And that's it.

Solution 2

DECLARE  
 @saveas VARCHAR(2048)
,@query VARCHAR(2048)
,@bcpquery VARCHAR(2048)
,@bcpconn VARCHAR(64)
,@bcpdelim VARCHAR(2)

 SET @query      = 'select * from table1'
 SET @saveas     = '\SERVER1SHARE1FOLDERQueryOutput.txt'
 SET @bcpdelim   = '|'
 SET @bcpconn    = '-T' -- Trusted
 --SET @bcpconn    = '-U <username> -P <password>' -- SQL authentication


 SET @bcpquery = 'bcp "' + replace(@query, char(10), '') + '" QUERYOUT "' + @saveas + '" -c -t^' + @bcpdelim + ' ' + @bcpconn + ' -S ' + @@servername
EXEC master..xp_cmdshell @bcpquery  

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...