T-SQL:如何成功地将Null值转换为日期类型?

时间:2017-09-01 06:48:46

标签: sql-server-2008 tsql date

在我的例子中,我有一个包含1列日期的表,我插入3个值,其中1个为null。正如您在第一个选择中看到的那样,null值在order by之后首先出现。在2选择中,虽然我将一个字符串作为日期转换,但是在order by之后的先前空值仍然是第一个。这是我的查询,如果您运行它,您将更好地理解问题!我也试过转换

drop table table1

create table table1(
dates date)

insert into table1 values ('2017-9-1'),('2017-7-1'),(NULL)

select dates from table1 ORDER BY dates ASC

select ISNULL(dates,CAST('2020-04-25T15:50:59.997' AS date))from table1 ORDER BY dates ASC

select ISNULL(dates, '2017-8-1')from table1 ORDER BY dates ASC

1 个答案:

答案 0 :(得分:1)

在所有的select语句中,您按日期字段排序 - 也许您想按表达式排序?

例如:

select dates from table1 ORDER BY dates ASC

select dates from table1 ORDER BY ISNULL(dates,CAST('2020-04-25T15:50:59.997' AS date)) ASC

select dates from table1 ORDER BY ISNULL(dates, '2017-8-1') ASC

select dates from table1 ORDER BY dates ASC

select ISNULL(dates,CAST('2020-04-25T15:50:59.997' AS date))from table1 
ORDER BY ISNULL(dates,CAST('2020-04-25T15:50:59.997' AS date)) ASC

select ISNULL(dates, '2017-8-1')from table1 
ORDER BY ISNULL(dates, '2017-8-1') ASC

或者您可以使用子查询

SELECT dates from ( 
  SELECT 
    ISNULL(dates,CAST('2020-04-25T15:50:59.997' AS date)) dates 
  FROM table1
) qry 
ORDER BY dates