I am trying to add column headers while extracting the table data, but my query throws the following error:
Invalid column name 'JobTaskID'.
ORDER BY items must appear in the select list if the statement contains a UNION, INTERSECT or EXCEPT operator.
This is my query
SELECT
'JobTaskID', 'Geo', 'Environment', 'JobName', 'JobStarttime', 'JobEndtime',
'JobProcessingTime', 'JobTaskname', 'TaskStarttime', 'TaskEndtime',
'TaskProcessingTime', 'TotalActiveInventory', 'NewInventoryAdded',
'TotalActiveSKUs', 'TotalActiveStores', 'TotalCalculatedAllocations',
'TotalActiveAllocations'
UNION ALL
SELECT
CAST([JobTaskID] AS NVARCHAR(MAX)),
CAST([Geo] AS NVARCHAR(MAX)),
CAST([Environment] AS NVARCHAR(MAX)),
CAST([JobName] AS NVARCHAR(MAX)),
CAST([JobStarttime] AS NVARCHAR(MAX)),
CAST([JobEndtime] AS NVARCHAR(MAX)),
CAST([JobProcessingTime] AS NVARCHAR(MAX)),
CAST([JobTaskname] AS NVARCHAR(MAX)),
CAST([TaskStarttime] AS NVARCHAR(MAX)),
CAST([TaskEndtime] AS NVARCHAR(MAX)),
CAST([TaskProcessingTime] AS NVARCHAR(MAX)),
CAST([TotalActiveInventory] AS NVARCHAR(MAX)),
CAST([NewInventoryAdded] AS NVARCHAR(MAX)),
CAST([TotalActiveSKUs] AS NVARCHAR(MAX)),
CAST([TotalActiveStores] AS NVARCHAR(MAX)),
CAST([TotalCalculatedAllocations] AS NVARCHAR(MAX)),
CAST([TotalActiveAllocations] AS NVARCHAR(MAX))
FROM
ctbl_jobReport
ORDER BY
JobTaskID
The table ctbl_jobreport
does contain the JobTaskID
column:
CREATE TABLE [dbo].[ctbl_jobReport]
(
[JobTaskID] [int] NOT NULL IDENTITY(1, 1),
[Geo] [nvarchar] (128) COLLATE Latin1_General_CI_AS NULL,
[Environment] [nvarchar] (128) COLLATE Latin1_General_CI_AS NULL,
[JobName] [nvarchar] (128) COLLATE Latin1_General_CI_AS NULL,
[JobStarttime] [datetime] NULL,
[JobEndtime] [datetime] NULL,
[JobProcessingTime] [nvarchar] (128) COLLATE Latin1_General_CI_AS NULL,
[JobTaskname] [nvarchar] (128) COLLATE Latin1_General_CI_AS NULL,
[TaskStarttime] [datetime] NULL,
[TaskEndtime] [datetime] NULL,
[TaskProcessingTime] [nvarchar] (128) COLLATE Latin1_General_CI_AS NULL,
[TotalActiveInventory] [int] NULL,
[NewInventoryAdded] [int] NULL,
[TotalActiveSKUs] [int] NULL,
[TotalActiveStores] [int] NULL,
[TotalCalculatedAllocations] [int] NULL,
[TotalActiveAllocations] [int] NULL
) ON [PRIMARY]
When I run the two select statements individually, I do not see that error
2条答案
按热度按时间sg24os4d1#
Putting aside why you would want to do something like this (which is almost certainly trying to solve a different problem with the wrong kind of solution), you can achieve it by correctly aliasing the fields (as you're using a
UNION
) so they can be sorted on, and then adding an additional static field to force the "column headers" to be returned first, before the actual data:kuhbmx9i2#
Create a db.view then apply the separate query Select * from db.view order by JobTaskID