SQL Server stored procedure to export Select Result to CSV

大城市里の小女人 提交于 2019-12-24 13:26:28

问题


In my stored procedure, I want to export select result to a .CSV file. I need to write a stored procedure which selects some data from different tables and saves it to a .CSV file.

Selecting part is ready

 SELECT DISTINCT 
                  PER.NREGNUMBER_PERNUM AS [Registration Number], 
                  PER.CFAMNAME_PER AS [Family Name], 
                  PER.CGIVNAME_PER AS [Given Name], 
                  CONVERT(varchar(10), CONVERT(date, PER.DBIRTHDATE_PER, 106), 103) AS [Birth Date], 
                  PER.CGENDER_PERGEN as [Gender],
                  PHONE.MOBILE_NUMBER
        FROM      PERSON AS PER 
                  LEFT OUTER JOIN
                  PHONE ON PER.NREGNUMBER_PERNUM = PHONE.NREGNUMBER_PPHPER AND PHONE.CPRIMARY_PPH = 'Y'

回答1:


The task was I had to export from database some data to .CSV at specified time. In the begining we wanted to use windows scheduler for running stp. The STP had to be able to export data. But I couldn't find a way. Instead the thing what we did was creating simple STP which brings only data . And we created batch file which calls STP and export result to .CSV file. The batch file is simple

sqlcmd -S Etibar-PC\SQLEXPRESS -d MEV_WORK -E -Q "dbo.SelectPeople" -o "MyData1.csv" -h-1 -s"," -w 700

dbo.SelectPeople is STP
Etibar-PC\SQLEXPRESS is Schema
MEV_WORK is Database name.




回答2:


i have build a procedure to help you all

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

-- example exec Sys_Database_exportToCsv 'select MyEmail from 
QPCRM.dbo.Myemails','D:\test\exported.csv'

create PROCEDURE Sys_Database_exportToCsv

(
@ViewName nvarchar(50),
@exportFile nvarchar(50)
)

AS

BEGIN

SET NOCOUNT ON;

EXEC sp_configure 'show advanced options', 1;  

RECONFIGURE; 

EXEC sp_configure 'xp_cmdshell', 1;  

RECONFIGURE; 

Declare @SQL nvarchar(4000)

Set @SQL = 'Select * from ' + 'QPCRM.dbo.Myemails'

Declare @cmd nvarchar(4000)

SET @cmd = 'bcp '+CHAR(34)+@ViewName+CHAR(34)+' queryout 
'+CHAR(34)+@exportFile+CHAR(34)+' -S '+@@servername+' -c -t'+CHAR(34)+','+CHAR(34)+' -r'+CHAR(34)+'\n'+CHAR(34)+' -T'

exec master..xp_cmdshell @cmd

EXEC sp_configure 'xp_cmdshell', 0;  

RECONFIGURE; 

EXEC sp_configure 'show advanced options', 0;  

RECONFIGURE; 

END

GO



回答3:


To create a CSV string from you table result follow the instruction on

http://blog.sqlauthority.com/2009/11/25/sql-server-comma-separated-values-csv-from-table-column/

As far as I know there is no way to save data into a file on disk directly using TSQL. To save a file, you can create a SQL-CLR stored procedure instead of a TSQl one in which you can use regular C# code.



来源:https://stackoverflow.com/questions/26773962/sql-server-stored-procedure-to-export-select-result-to-csv

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