2016-01-20 67 views
1

我正在嘗試所選案例的SQL語句。 'when'有一個日期轉換。這是拋出錯誤。我錯過了什麼?選擇大小寫轉換日期

SELECT DISTINCT 
    'detail', n.UserName, n.StatusCodeDesc, 
    CASE 
     WHEN n.enddate IS NULL AND (n.statuscode = 'L' or n.statuscode = 'P') 
     THEN (CONVERT(VARCHAR(10), getdate(), 101) AS [MM/DD/YYYY]) 
     ELSE (CONVERT(VARCHAR(10), n.EndDate, 101) AS [MM/DD/YYYY]) 
    END, 
    n.TC_OBT_STAT 
FROM 
    tbl_ActNightlyFeed n 
INNER JOIN 
    Tbl_ActExistingFeed g ON n.Empid = g.Empid 
+1

你能讓我知道錯誤是什麼嗎? –

回答

4

列別名應該只出現的情況下表達結束後,像這樣:

SELECT DISTINCT 
    'detail', 
    n.UserName, 
    n.StatusCodeDesc, 
    CASE 
    WHEN n.enddate IS NULL AND (n.statuscode = 'L' OR n.statuscode = 'P') 
    THEN CONVERT(VARCHAR(10), getdate(), 101) 
    ELSE CONVERT(VARCHAR(10), n.EndDate, 101) 
    END AS [MM/DD/YYYY], 
    n.TC_OBT_STAT 
FROM tbl_ActNightlyFeed n 
JOIN Tbl_ActExistingFeed g ON n.Empid = g.Empid 
0

您沒有選擇g表都沒有。我建議寫這篇爲:

SELECT 'detail', n.UserName, n.StatusCodeDesc, 
     (CASE WHEN n.enddate IS NULL AND n.statuscode IN ('L', 'P') 
      THEN CONVERT(VARCHAR(10), getdate(), 101) 
      ELSE CONVERT(VARCHAR(10), n.EndDate, 101) 
     END) AS [MM/DD/YYYY], 
     n.TC_OBT_STAT 
FROM tbl_ActNightlyFeed n 
WHERE EXISTS (SELECT 1 
       FROM Tbl_ActExistingFeed g 
       WHERE n.Empid = g.Empid 
      ); 

如果夜間飼料表可能導致重複,你仍然需要select distinct。我猜這張桌子不會有重複。