问题
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