2016-02-12 65 views
0

我在Northwind數據庫上進行培訓,但被困在案例陳述中,我在下面放置查詢並希望得到援助。Null的案件表達問題

問題是我希望Shippeddate列中的記錄在這種情況下有一些文本,當它有NULL的時候我放置了'ddd',但是NULL不斷出現在結果集中。

SELECT OrderID, 
     CONVERT(VARCHAR(10), OrderDate, 103) AS OrderDate, 
     CONVERT(VARCHAR(10), RequiredDate, 103) AS RequiredDate, 
     CASE ShippedDate 
     WHEN NULL THEN 'ddd' 
     ELSE CONVERT(VARCHAR(10), ShippedDate, 103) 
     END          AS ShippedDate 
     -- Why is this not working 
     , 
     [UnitPrice]        AS UnitPriceOnOrder, 
     [Quantity]        AS QuantityOnOrder, 
     [Discount]        AS DiscountOnOrder, 
     CompanyName_II       AS CustomerCompanyName, 
     ContactName_II       AS CustomerContact, 
     ContactTitle_II       AS CustomerContactTitle, 
     City_II         AS CustomerCity, 
     Country_II        AS CustomerCountry, 
     ProductName, 
     CategoryName, 
     [Description]       AS CategoryDescription, 
     UnitsInStock, 
     UnitsOnOrder, 
     UnitsInStock - UnitsOnOrder    AS AvailableUnitsInStock, 
     FirstName + ' ' + LastName    AS EmployeeName 
FROM ##NorthwindTestI 
WHERE [Quantity] > 10 
     AND ShippedDate > '19970101' 
     OR [UnitPrice] > 10 
     OR Country_II = 'USA' 
     OR FirstName + ' ' + LastName = 'Janet Leverling' 
ORDER BY 
--[Quantity] 
ShippedDate 
+0

感謝編輯蒂姆。 –

回答

0

使用WHEN ShippedDate IS NULL,而不是CASE ShippedDate WHEN NULL

SELECT ....., 
     CASE WHEN ShippedDate IS NULL 
     THEN 'ddd' 
     ELSE CONVERT(VARCHAR(10), ShippedDate, 103) 
     END AS ShippedDate 
..... 
1

嘗試使用ISNULL()代替:

因此而不是

CASE ShippedDate 
     WHEN NULL THEN 'ddd' 
     ELSE CONVERT(VARCHAR(10), ShippedDate, 103) 
     END          AS ShippedDate 

使用:

ISNULL(CONVERT(VARCHAR(10),ShippedDate,103),'ddd') 

所以您的查詢就會像:

SELECT OrderID, 
     CONVERT(VARCHAR(10), OrderDate, 103) AS OrderDate, 
     CONVERT(VARCHAR(10), RequiredDate, 103) AS RequiredDate, 
     ISNULL(CONVERT(VARCHAR(10),ShippedDate,103),'ddd') AS ShippedDate 
     -- Why is this not working 
     , 
     [UnitPrice]        AS UnitPriceOnOrder, 
     [Quantity]        AS QuantityOnOrder, 
     [Discount]        AS DiscountOnOrder, 
     CompanyName_II       AS CustomerCompanyName, 
     ContactName_II       AS CustomerContact, 
     ContactTitle_II       AS CustomerContactTitle, 
     City_II         AS CustomerCity, 
     Country_II        AS CustomerCountry, 
     ProductName, 
     CategoryName, 
     [Description]       AS CategoryDescription, 
     UnitsInStock, 
     UnitsOnOrder, 
     UnitsInStock - UnitsOnOrder    AS AvailableUnitsInStock, 
     FirstName + ' ' + LastName    AS EmployeeName 
FROM ##NorthwindTestI 
WHERE [Quantity] > 10 
     AND ShippedDate > '19970101' 
     OR [UnitPrice] > 10 
     OR Country_II = 'USA' 
     OR FirstName + ' ' + LastName = 'Janet Leverling' 
ORDER BY 
--[Quantity] 
ShippedDate 
+0

非常感謝你們,這兩種解決方案都很有效,非常出色。 –

+0

@AlbertoCaeiro您的歡迎 –