I need best practice in T-SQL Export data to CSV (with header)

我怕爱的太早我们不能终老 提交于 2019-11-30 21:30:03

You could use a UNION to create a header row, like this:

SELECT 'object_id', 'name'

UNION ALL

SELECT object_id, name
FROM sys.tables
ravi

Execute the below command in SQL Server:

EXEC xp_cmdshell 'SQLCMD -S . -d MsVehicleReg2 -Q "SELECT * FROM tempViolationInfo" -s "," -o "O:\result.csv"';

Here is the T-SQL way:

INSERT INTO OPENROWSET('Microsoft.ACE.OLEDB.12.0','Text;Database=D:\;HDR=YES;FMT=Delimited','SELECT * FROM [FileName.csv]')
SELECT Field1, Field2, Field3 FROM DatabaseName

But, there's a couple of caveats:

  1. You need to have the Microsoft.ACE.OLEDB.12.0 provider available. The Jet 4.0 provider will work, too, but it's ancient, so I used this one instead.

  2. The .CSV file will have to exist already. If you're using headers (HDR=YES), make sure the first line of the .CSV file is a delimited list of all the fields.

For Ace.OLEDB.12.0 (the new Jet redistributable engine), you can install the 32-bit or 64-bit stand-alone engine, even if you have the "other flavor" already installed, whether on its own, from Access, etc:

use the /passive command-line option:

(32-bit): AccessDatabaseEngine.exe /passive (64-bit): AccessDatabaseEngine_64.exe /passive

In my case, I have 64-bit SQL Express 2008 R2, and had 32-bit Office 12 apps installed (thus, the 32-bit ACE drivers were installed). I installed the 64-bit AccessDatabaseEngine_64.exe, and it's sort of working for me now...

Also, this is assuming you've done the other configuration work:

EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1 GO

EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1 GO

sp_configure 'show advanced options', 1; GO RECONFIGURE; GO sp_configure 'Ad Hoc Distributed Queries', 1; GO RECONFIGURE; GO

user1390375

regarding "best practice", there is no best practice. there are several options available, not limited to:

  • in T-SQL with INSERT INTO OPENROWSET(...) SELECT * from [MyTable]...

  • executing BCP, whether from a job step or in T-SQL with xp_cmdshell

  • SSIS packages

  • PowerShell (from a job step, in SQL Server 2008+) or other external script/executable

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