Using BCP in a SQL query

时间:2015-07-13 20:59:45

标签: sql-server export bcp export-to-text

I have a stored procedure that updates several columns in a table and then selects out those columns so I can save them out for a report I run. Currently I am doing the exporting and saving manually though by setting column size in 'Query Options' to 333, turning off all the other options, putting the results to text and then saving the file out with the name and format. I know that there must be a way to automate this though the export and save process though.

I looked into using a job with Vb script, but this is a simple report that is run on demand and not on a schedule; so a job seemed to be overkill. The other option I found was BCP, which looks like what I need. I only know of this as a CMD tool though and can't quite figure out how to leverage this within a SQL query. In case it is needed here is an example of what my stored procedure is doing. Any help is appreciated and thank you in advance. I am using SQL 2008 R2 btw.

 UPDATE Table#1 SET Column1 = '' WHERE Column1 = 'XX'

UPDATE Table#1 SET Column2 = '' WHERE Column2 = '000000'



 SELECT   Column1 + 
          Column2 + 
          Column3  
 FROM Table#1 Where Column4 = 'T'

1 个答案:

答案 0 :(得分:2)

BCP是一个命令行实用程序,但是可以使用XP命令Shell通过SQL进行访问,因此您需要启用xp_cmdshell。以下是如何在SQL

中调用它的参数化示例
DECLARE @Server varchar(50) = 'ServerName' /* Source SQL Server */
DECLARE @FileName varchar(50) = ''
DECLARE @SourceProc varchar(50) = ''
DECLARE @sql varchar(8000)
DECLARE @RunDate varchar(10) = REPLACE(CONVERT(date, getdate()), '-','')
DECLARE @FilePath as varchar(255) = '\\UNCPathtoOutputFile\'
DECLARE @StartDate as Date = (select dateadd(month,datediff(month,0,GETDATE())-2,0))--'1/1/2013' /* Example of required Date as parameter */
DECLARE @EndDate as Date = (SELECT dateadd(month,datediff(month,0,GETDATE())-0,-1))--'2/1/2013' /* Example of required Date as parameter */
--  BCP Export
    SET @SourceProc = '[Schema].[StoredProcName]'
    SET @FileName = 'SomeOutputFile' + @RunDate + '.txt'
    SET @FilePath = @FilePath + @FileName
    SET @sql = 'bcp "EXEC [Database].' + @SourceProc + ' ''' + CONVERT(varchar(10),@StartDate, 101) + ''',''' + CONVERT(varchar(10),@EndDate, 101) + '''" QUERYOUT "' + @FilePath + '" -c -t"|" -r\n -S' + @Server + ' -T'

    --PRINT(@SQL)
    exec master.dbo.xp_cmdshell @sql