我想在我的sql查询中包含这个Case语句,但是我收到了这个错误:列名无效:MsgID。有没有人有任何关于代码如何运行此错误的建议?请注意我使用的是SQL Server management studio 2008。
CASE WHEN MsgID = '1' THEN SUBSTRING(Parms,1,6) +' Was removed from:'
WHEN MsgID = '2' THEN 'This Move List has been cleared of all its media'
ELSE '' -- Optional Else
END AS [RemovalPath],
;WITH CTE AS
(
SELECT CONVERT(DATETIME,LEFT([Date],8)+' '+
SUBSTRING([Date],10,2)+':'+
SUBSTRING([Date],12,2)+':'+
SUBSTRING([Date],14,2)+'.'+
RIGHT([Date],3)) [Date],
ItemId,
Parms,
[OBJECT]
FROM ( SELECT ItemId,
CONVERT(VARCHAR(18),[Date]) [Date],
Parms,
[OBJECT]
FROM JnlList
WHERE UserCode = 'Automation') A
)
SELECT ItemId,
CONVERT(DATE,[Date]) [Date],
CONVERT(VARCHAR(10),[Date],108) AS [Time],
SUBSTRING(Parms,1,6) +' Was removed from:' RemovalPath,
[OBJECT] [Move List:]
FROM CTE
WHERE [Date] >= CONVERT(DATE,DATEADD(DAY,-4,GETDATE()))
WITH CTE AS
(
SELECT CONVERT(DATETIME,LEFT([Date],8)+' '+
SUBSTRING([Date],10,2)+':'+
SUBSTRING([Date],12,2)+':'+
SUBSTRING([Date],14,2)+'.'+
RIGHT([Date],3)) [Date],
ItemId,
MsgID,
Parms,
[OBJECT]
FROM ( SELECT ItemId,
CONVERT(VARCHAR(18),[Date]) [Date],
Parms,
[OBJECT]
FROM JnlList
WHERE UserCode = 'Automation') A
)
SELECT ItemId, MsgID,
CONVERT(DATE,[Date]) [Date],
CONVERT(VARCHAR(10),[Date],108) AS [Time],
CASE WHEN MsgID = '1' THEN SUBSTRING(Parms,1,6) +' Was removed from:'
WHEN MsgID = '2' THEN 'This Move List has been cleared of all its media'
ELSE '' -- Optional Else
END AS [RemovalPath],
[OBJECT] [Move List:]
FROM CTE
WHERE [Date] >= CONVERT(DATE,DATEADD(DAY,-4,GETDATE()))
答案 0 :(得分:3)
导致问题的不是case语句,它是CTE声明 - 内部MsgId
语句中没有SELECT
列,因此您不能将其包含在外部的列列表中。
答案 1 :(得分:0)
您不会将MsgId
(可能)JnlList
展示为A
,此处:
FROM ( SELECT ItemId,
CONVERT(VARCHAR(18),[Date]) [Date],
Parms,
[OBJECT]
FROM JnlList
WHERE UserCode = 'Automation') A
因此,您可能只需要将MsgId
添加到该SELECT
子句中。如果它不是来自该表,请告诉我们它的来源。