有关存储过程的快速帮助。添加标题以输出

时间:2014-04-17 14:37:07

标签: sql-server-2008 stored-procedures export

如何修改此存储过程以在导出中输出标题?它在分配给SQL Server代理时与bcp实用程序一起使用,但我需要让文件也导出文件中的标题(以及select的内容)

CREATE PROCEDURE [dbo].[GL_Export] 
AS
    DECLARE @gl table 
   (AccCode VARCHAR(3000),
    CodeDesc VARCHAR(3000),
    AccountType_id VARCHAR(3000),
    AccGroupName VARCHAR(3000)
   )

  -- Inserts data into @temptable (memory) 
  INSERT  @gl
    SELECT DISTINCT 
        RTRIM (s1.SGMNTID) AS 'AccCode',RTRIM (s1.DSCRIPTN) AS 'CodeDesc', 
        CASE
           WHEN s1.SGMTNUMB = '1' THEN '1' 
           WHEN s1.SGMTNUMB = '2' THEN '2'
           WHEN s1.SGMTNUMB = '3' THEN '110'
           WHEN s1.SGMTNUMB = '4' THEN '4'
           WHEN s1.SGMTNUMB = '5' THEN '120'
        END AS 'AccountType_id',
        CASE 
           WHEN s1.SGMTNUMB = '2' THEN LEFT(s1.SGMNTID, 2)
           ELSE 'DEFAULT'
        END AS 'AccGroupName'
    FROM 
        GL40200 s1

    UNION 

    SELECT  
        REPLACE ([ACTNUMBR_1] + '-' + [ACTNUMBR_2] + '-'
                 + [ACTNUMBR_3] + '-' +[ACTNUMBR_4] + '-'
                 + [ACTNUMBR_5], ' ', '') AS 'AccCode',
        '' AS 'CodeDesc',
        '0' AS 'AccountType_id',
        'Default' AS 'AccGroupName'
    FROM 
        GL00100 a

    -- Selects the output for memory and should add headers to file
    SELECT
        AccCode, CodeDesc, AccountType_id, AccGroupName 
    FROM @gl

    UNION


    Select AccCode,CodeDesc,AccountType_id,AccGroupName from @gl


    GO

1 个答案:

答案 0 :(得分:1)

您可以使用UNION ALL并使一个SELECT具有列标题,然后使用实际值转换为varchar

SELECT 'AccCode', 'CodeDesc', 'AccountType_id', 'AccGroupName'

UNION ALL

SELECT
    CAST(AccCode AS varchar(100)), 
    CAST(CodeDesc AS varchar(100)),
    CAST(AccountType_id AS varchar(100)),
    CAST(AccGroupName AS varchar(100))
FROM @gl

(当然,如果某些列已经是非数字的,您可以将它们保留为非数字,否则CAST视情况而定。)