Stored procedure that exports data into csv files only exports to one file

后端 未结 1 1083
醉梦人生
醉梦人生 2020-11-30 13:19

I have a fun script:

DECLARE @StartDT DATE
DECLARE @MinDOS DATE
DECLARE @TableName VARCHAR(50)
SET @TableName = \'ViewAccountDetail\'
SELECT @MinDOS = MIN(do         


        
相关标签:
1条回答
  • 2020-11-30 13:58

    Seems to work fine for me. I have a few suggestions:

    (1) stop doing all that string concatenation to build a date. You can do the same thing much easier as in:

    SELECT @StartDT = DATEADD(MONTH, DATEDIFF(MONTH, '19000101', @MinDOS), '19000101');
    

    (2) stop declaring varchar without length. And to ensure the right output, I prefer convert:

    SET @FileLocation = 'C:\test\' + @TableName
       + CONVERT(CHAR(10), @StartDT, 120) + '.csv';
    

    (3) instead of "debugging" the code by running the stored procedure and inspecting the output in the folder, why not sanity-check your input first? Also, why use two variables for the date?

    DECLARE 
       @StartDT DATE, 
       @TableName NVARCHAR(50), 
       @FileLocation VARCHAR(255);
    
    SET @TableName = N'ViewAccountDetail';
    
    SELECT @StartDT = DATEADD(MONTH, DATEDIFF(MONTH, '19000101', MIN(dos)), '19000101')
       FROM dbo.accn_demographics;
    
       PRINT @StartDT;
    -- ^^^^^ debugging 101 - what month do we think we're starting at?
    
    WHILE @StartDT < '20110901'
    BEGIN
        SET @FileLocation = 'C:\test\' + @TableName
          + CONVERT(CHAR(10), @StartDT, 120) + '.csv';
    
          PRINT @FileLocation;
        --^^^^^ again, debugging 101 - what does the filename currently look like?
    
        --EXEC BCP_Text_File @TableName, @FileLocation    
        SET @StartDT = DATEADD(MONTH, 1, @StartDT);
    END
    
    0 讨论(0)
提交回复
热议问题