我意识到还有其他线程覆盖了这一点,但我找不到解决我问题的线程。
我有三个文本列,要么包含日期,要么不包含任何内容(null(,我将文本转换为日期,以便在日期进入Excel后使用日期过滤器。
显然,null 值被转换为"1900-01-01",但我找不到将它们显示为空白的方法,即使使用子查询也是如此。
这就是我正在做的...
Select top 999999999
OtherFields,
case when Engdate = '19000101' then '' else Engdate end as 'EngDate',
OtherOtherFields
from
(
select
OtherFields,
case
when VAR_AppID = '3' then nullif( CONVERT(date,concat(right([2201],4),
SUBSTRING([2201],4,2), left([2201],2))),null)
else nullif( CONVERT(date,concat(right([3429],4),
SUBSTRING([3429],4,2), left([3429],2))),null) end as 'Engdate',
case when ([2201] is not null and Len([2201]) = 10 ) then
CONVERT(date,concat(right([2201],4), SUBSTRING([2201],4,2), left([2201],2)))
else null end as 'EngagementRec',
OtherOtherFields
from
Tables
)
字段 [2201] 和 [3429] 是包含"日/月/年"格式的日期的文本字段。
我是否应该隐蔽地回到文本格式以允许"显示空白 - 如果是这样,日期是否仍被识别为日期?
根据 Anthony Green 在 sqlservercentral 上的回答,您可以尝试:
ISNULL(CONVERT(varchar, DateTimeColumnName,23),'') as DateTimeColumnName
是的,首先转换它们的文本不会有任何坏处(我认为(。 请尝试以下操作:
Select top 999999999
OtherFields,
case when Engdate = '19000101' then '' else CONVERT(CHAR(10), EngDate, 120) end as 'EngDate' end as 'EngDate',
OtherOtherFields
from
(
select
OtherFields,
case
when VAR_AppID = '3' then nullif( CONVERT(date,concat(right([2201],4),
SUBSTRING([2201],4,2), left([2201],2))),null)
else nullif( CONVERT(date,concat(right([3429],4),
SUBSTRING([3429],4,2), left([3429],2))),null) end as 'Engdate',
case when ([2201] is not null and Len([2201]) = 10 ) then
CONVERT(date,concat(right([2201],4), SUBSTRING([2201],4,2), left([2201],2)))
else null end as 'EngagementRec',
OtherOtherFields
from
Tables
)
谢谢。
如您所知,将空字符串转换为日期数据类型将返回 1900-01-01。
示例 SQL:
SELECT CAST ('' as date) AS [thedate]
返回:
thedate
1900-01-01
强制转换为日期数据类型时,NULL 值仍为 NULL。 根据您的代码,我认为您所要做的就是更改这一行:
case when Engdate = '19000101' then '' else Engdate end as 'EngDate',
自:
case when Engdate = '19000101' then NULL else Engdate end as 'EngDate',
我自己关闭了这个,因为我找不到任何有用的东西。 案例语句、ISNULL((、NULLIF(( 等的任意组合都会导致 NULL 或 '1900-01-01'。转换为文本会使日期字段在 Excel 中不可用。
由于数据将进入Excel数据透视表,因此我并不迫切需要解决此问题,因为数据透视表无论如何都会消除空值。
。如果我需要在列表中显示数据,我可能会回到这个问题。
感谢所有提出建议的人!
根据 Concat 函数的 ms 帮助(这是 sql 2012 以后而不是 2008( https://learn.microsoft.com/en-us/sql/t-sql/functions/concat-transact-sql?view=sql-server-2017
如果 CONCAT 收到包含所有 NULL 值的参数,它将返回一个空 瓦尔查尔(1( 类型的字符串。
零长度字符串将隐式转换为零,从而在 sql 服务器中为您提供零日期。在尝试转换之前,您需要处理空值。 也许改用Try_convert。 使用带有正确选项的try_convert。 TRY_CONVERT(日期时间,列与字符串日期,103(