如何将空日期值转换为varchar并在SQL中使用where语句

问题描述

我被告知要获得1996年5月5日之后发出的所有订单,其中包括未发货的订单。
NULL值应为“未发货”。可以,但是我不能再比较日期了。
我确定有一种我不知道的正确执行方法。有什么想法吗?

SELECT [OrderID] AS 'Order Number',CASE 
    WHEN [ShippedDate] IS NULL THEN 'Not Shipped' 
END AS 'Shipped Date' 
FROM Orders
WHERE [ShippedDate] IS NULL OR [ShippedDate] > '05/06/1996' -- This line doesn't work

解决方法

由于data type precedence的规则,@ HABO指出,将ELSE [ShippedDate]添加到大小写表达式将不起作用,这将导致'Not Shipped'未能成功转换以匹配{的数据类型{1}}。假设ShippedDate是日期时间数据类型。

运行以下示例将引发该异常:

ShippedDate

您将获得: enter image description here

根据这些规则,SQL Server正在将DECLARE @testdata TABLE ( [OrderID] INT,[ShippedDate] DATETIME ); INSERT INTO @testdata ( [OrderID],[ShippedDate] ) VALUES ( 1,GETDATE()),( 2,NULL ); SELECT [OrderID],CASE WHEN [ShippedDate] IS NULL THEN 'Not Shipped' ELSE [ShippedDate] END AS 'Shipped Date' FROM @testdata WHERE [ShippedDate] IS NULL OR [ShippedDate] > '1996-05-06'; --use a standard data format here 转换为'Not Shipped'列的数据类型,该值不是有效的日期时间并引发错误。

耦合选项,将其添加为另一列,在该列中您将返回ShippedDate,但是具有类似Status列的内容:

'Shipped Date'

为您提供以下结果:

SELECT [OrderID],[ShippedDate] --Give the shipped date as it's own separate column,CASE WHEN [ShippedDate] IS NULL THEN 'Not Shipped'
            ELSE 'Shipped' --Then have a Shipped status
       END AS 'Shipped Status'
FROM   @testdata
WHERE  [ShippedDate] IS NULL
       OR [ShippedDate] > '1996-05-06'; --use a standard data format here

如果必须将它们放在同一列中,则可以在语句的ELSE部分转换ShippedDate,使用FROMAT()它将为您转换,然后可以定义DATETIME的格式值返回:

OrderID     ShippedDate             Shipped Status
----------- ----------------------- --------------
1           2020-11-05 09:35:32.653 Shipped
2           NULL                    Not Shipped

为您提供以下结果:

SELECT [OrderID],CASE WHEN [ShippedDate] IS NULL THEN 'Not Shipped'
            ELSE FORMAT([ShippedDate],'yyyy-MM-dd')
       END AS 'Shipped Date'
FROM   @testdata
WHERE  [ShippedDate] IS NULL
       OR [ShippedDate] > '1996-05-06'; --use a standard data format here
,

尝试一下!

 SELECT [OrderID] AS 'Order Number',CASE 
        WHEN [ShippedDate] IS NULL THEN 'Not Shipped' 
        else [ShippedDate]
    END AS 'Shipped Date' 
    FROM Orders
    WHERE [ShippedDate] IS NULL OR [ShippedDate] > '05/06/1996'
,

使用标准日期格式:

WHERE ShippedDate IS NULL OR
      ShippedDate > '1996-05-06'