2014-04-18 59 views
-1

我已經在存儲過程中創建了該代碼,它的工作原理類似於一個魅力:但現在我的軟件提供商要求我也包含列名。已經嘗試了幾百個小時,現在總是關閉,但從來沒有取得成功。誰能幫我。如何爲BCP命名列?

謝謝!

-- ============================================= 
-- Author:  <blablabla> 
-- Create date: <2014/04/16> 
-- Description: <Export Orders to csv> 
-- ============================================= 
ALTER PROCEDURE [dbo].[transfertofile] 
AS 
    -- SET NOCOUNT ON added to prevent extra result sets from 
    -- interfering with SELECT statements. 
    SET NOCOUNT ON; 
    DECLARE @return_value int 
IF EXISTS (Select 1 From dbo.temp_updated) 
    BEGIN 
    DECLARE @sql varchar (8000) 

SELECT @sql ='bcp "Select Detail, SectionRelease, 1, WMS80.dbo.temp_updated.OrderNumber, WMS80.dbo.PickingDetail.LineNumber, WMS80.dbo.PickingDetail.ItemNumber, CAST(WMS80.dbo.PickingDetail.ActualQuantity AS NUMERIC(10)), WMS80.dbo.temp_updated.UDF01, WMS80.dbo.temp_updated.UDF02, WMS80.dbo.PickingDetail.PickFrom FROM WMS80.dbo.temp_updated, WMS80.dbo.PickingDetail WHERE WMS80.dbo.temp_updated.OrderNumber = WMS80.dbo.PickingDetail.OrderNumber" queryout "C:\bcptest.txt" -U user -P password -c -S servername -t,' 

EXEC xp_cmdshell @sql 

--delete at the end 
TRUNCATE TABLE WMS80.dbo.temp_updated 


DECLARE 
@TodayDate as varchar(40), 
@TodayHour as varchar(40), 
@TodayMinu as varchar(40), 
@TodaySeco as varchar(40), 
@NewFileName as varchar(100), 
@cmdstr as varchar(128) 
SELECT @TodayDate = CONVERT(varchar(10), GETDATE(), 112) 
SELECT @TodayHour = DATEPART(hh,GETDATE()) 
SELECT @TodayMinu = DATEPART(mi,GETDATE()) 
SELECT @TodaySeco = DATEPART(SS,GETDATE()) 
SELECT @NewFileName = 'ExportOrders' + '_' + @TodayDate + '_' + @TodayHour + '_' + @TodayMinu + '_' + @TodaySeco + '.csv' 
print @NewFileName 
set @cmdstr='MOVE /Y C:\bcptest.txt C:\' + @NewFileName 
print @cmdstr 
EXEC master..xp_cmdshell @cmdstr 

END 
else 
    BEGIN 
     return 
    end 

回答

0

在bcp查詢中使用UNION語句將列名硬編碼到輸出文件中。這意味着您必須將所有內容導出爲varchar/string,因爲每列都將以varchar格式包含其名稱作爲第一個條目。

@sql ='bcp "SELECT 'Detail', 'SectionRelease', '1', 'OrderNumber', 'LineNumber','ItemNumber', 'ActualQuantity', 'UDF01', 'UDF02', 'PickFrom', 'PickingDetail' 
UNION SELECT Detail, SectionRelease, 1, WMS80.dbo.temp_updated.OrderNumber, WMS80.dbo.PickingDetail.LineNumber, WMS80.dbo.PickingDetail.ItemNumber, WMS80.dbo.PickingDetail.ActualQuantity, WMS80.dbo.temp_updated.UDF01, WMS80.dbo.temp_updated.UDF02, WMS80.dbo.PickingDetail.PickFrom FROM WMS80.dbo.temp_updated, WMS80.dbo.PickingDetail WHERE WMS80.dbo.temp_updated.OrderNumber = WMS80.dbo.PickingDetail.OrderNumber" queryout "C:\bcptest.txt" -U user -P password -c -S servername -t,'