How to return T-SQL query with column names as first row

一世执手 提交于 2020-04-13 07:32:20

问题


I'm writing a SSIS package to output data from a SQL Server 2012 database to a .CSV file for a client. The requirement is that the first row be the column names. Below is the query I've written for the Source in the Data Flow Task. The problem is, it always returns the column names as the LAST row, not the first. Why? How do I achieve this?

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

回答1:


How do I achieve this?

Don't do it through SQL.

Just tick the Column names in the first data row box in the Flat File Connection Manager and leave the original query untouched.

The column headers will then be added automatically without you needing to union this additional metadata (and potentially cast everything as a string on the SQL side).




回答2:


You could try UNION ALL:

SELECT
'Edit Set' AS 'Edit Set', 'Employee No.' AS 'Employee No.'
FROM LatestEligible
UNION ALL
SELECT DISTINCT
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


来源:https://stackoverflow.com/questions/55766513/how-to-return-t-sql-query-with-column-names-as-first-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!