Sql server 2008 T-SQL:如何成功地将空值强制转换为日期类型?
在我的示例中,我有一个表,其中有1列日期,我插入了3个值,其中1个值为null。正如您在第一个select中所看到的,null值在order by之后首先出现。在2 select中,虽然我将字符串转换为date,但order by之后的先前空值仍然是第一个。这是我的问题,如果你运行它,你会更好地理解问题!我也试过转换Sql server 2008 T-SQL:如何成功地将空值强制转换为日期类型?,sql-server-2008,tsql,date,Sql Server 2008,Tsql,Date,在我的示例中,我有一个表,其中有1列日期,我插入了3个值,其中1个值为null。正如您在第一个select中所看到的,null值在order by之后首先出现。在2 select中,虽然我将字符串转换为date,但order by之后的先前空值仍然是第一个。这是我的问题,如果你运行它,你会更好地理解问题!我也试过转换 drop table table1 create table table1( dates date) insert into table1 values ('2017-9-1'
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
在所有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 (
SELECT
ISNULL(dates,CAST('2020-04-25T15:50:59.997' AS date)) dates
FROM table1
) qry
ORDER BY dates
不确定您试图实现的目标-您希望/希望空值出现在哪里?正如您所看到的,我执行“按日期排序ASC”,因此在强制转换后,我希望前一个空值按未发生的其他值排序。因此,您需要按表达式排序(日期是字段,仍然包含空值)-请参阅我的答案
SELECT dates from (
SELECT
ISNULL(dates,CAST('2020-04-25T15:50:59.997' AS date)) dates
FROM table1
) qry
ORDER BY dates