如何以列名作为第一行返回T-SQL查询

时间:2019-04-19 18:54:57

标签: sql-server tsql ssis

我正在编写一个SSIS包,以将数据从SQL Server 2012数据库输出到客户端的.CSV文件中。要求第一行是列名。以下是我为数据流任务中的源编写的查询。问题是,它总是将列名返回为LAST行,而不是第一行。为什么?我该如何实现?

DECLARE @Today AS DateTime= GETDATE()
DECLARE @NextPayrollDate AS DateTime

EXEC mobile.getNextPayrollDate @Today, @NextPayrollDate OUTPUT

;WITH LatestEligible (EmployeeID, LatestBillVerified) AS
(
    SELECT 
        EmployeeID, MAX(DateBillVerified) AS LatestBillVerified
    FROM 
        Inv_DataReimbursement
    GROUP BY 
        EmployeeID
)
SELECT
    'Edit Set' AS 'Edit Set', 
    'Employee No.' AS 'Employee No.'
FROM 
    LatestEligible

UNION

SELECT 
    NULL AS 'Edit Set',
    d.EmployeeID AS 'Employee No.'
FROM 
    LatestEligible d
INNER JOIN 
    Employee e ON d.EmployeeID = e.EmployeeID
INNER JOIN 
    Inv_DataReimbursement dr ON d.EmployeeID = dr.EmployeeID 
                             AND d.LatestBillVerified = dr.DateBillVerified
WHERE 
    (dr.MonthlyServiceEligible = 'true'
     OR (dr.MonthlyServiceEligible = 'false' 
         AND e.DateEnd IS NOT NULL 
         AND e.DateEnd > @NextPayrollDate))
    AND dr.ActualAmount > 0

2 个答案:

答案 0 :(得分:3)

  

我该如何实现?

不要通过SQL来做。

只需在Flat File Connection Manager的第一条数据行中选中列名,并保持原始查询不变。

然后将自动添加列标题,而无需合并此其他元数据(并且可能在SQL端将所有内容强制转换为字符串)。

答案 1 :(得分:2)

您可以尝试Table: Person Attributes: person_id, firstName, lastName, age, birthday Partition Key: person_id

UNION ALL