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

别等时光非礼了梦想. 提交于 2019-12-02 02:12:36

问题


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


回答1:


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



回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/17781896/need-help-to-export-table-from-sql-server-2008-to-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!