简体   繁体   中英

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 '\n';

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 '\n'
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

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

  • 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.

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

 SET @query      = 'select * from table1'
 SET @saveas     = '\\SERVER1\SHARE1\FOLDER\QueryOutput.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  

To solved the error "SQL Server blocked access to procedure 'sys.xp_cmdshell' of component 'xp_cmdshell' because this component is turned off as part of the security configuration for this server." first do this.

-- To allow advanced options to be changed. EXEC sp_configure 'show advanced options', 1; GO -- To update the currently configured value for advanced options. RECONFIGURE; GO -- To enable the feature. EXEC sp_configure 'xp_cmdshell', 1; GO -- To update the currently configured value for this feature. RECONFIGURE; GO

More information here: http://msdn.microsoft.com/en-us/library/ms190693.aspx

  1. Right click on result set of SELECT from yourTable query
  2. Choose Save Results As...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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