Tsql 用空字符串替换空字符串的T-SQL
我有以下联合查询:Tsql 用空字符串替换空字符串的T-SQL,tsql,Tsql,我有以下联合查询: select 'type1' as type, id, add_date from Table A where type = type1 union all select 'type2' as type, id, '' as add_date from Table B 由于add_date不适用于类型2,它为返回的任何记录提供1900-01-01 00:00:00.000。我可以将语句从“”作为add_date更改为NULL作为add_date,但用
select
'type1' as type,
id,
add_date
from Table A
where type = type1
union all
select
'type2' as type,
id,
'' as add_date
from Table B
由于add_date不适用于类型2,它为返回的任何记录提供1900-01-01 00:00:00.000。我可以将语句从“”作为add_date更改为NULL作为add_date,但用户询问我是否可以从报告中删除NULL,并在适用的情况下将结果保留为空字符串。实现这一目标的最佳方式是什么?谢谢 您可以使用null并将结果转换为字符串,同时应用
ISNULL
函数:
SELECT [type], id, ISNULL(CAST(add_date as VARCHAR), '') AS add_date
FROM (
SELECT 'type1' as [type]
,id
,add_date
FROM TableA
UNION
SELECT 'type2' as [type]
,id
,null as add_date
FROM TableB
) inside_query
这将允许您提供空格,而不是1/1/1900或NULL
关键字。如果需要提供特定的日期格式,您还可以将转换
更改为转换。尝试以下操作:
select
'type1' as type,
id,
CAST(add_date AS VARCHAR) as add_date
from Table A
where type = type1
union all
select
'type2' as type,
id,
'' as add_date
from Table B
在第一个select中将add_date强制转换为字符类型(可能会破坏您的报告),在应用程序代码中将其替换为空字符串,并在B查询中选择NULL。要为其他RDBMS提供更方便的解决方案,请使用COALESCE()
而不是ISNULL()
。感谢您的快速响应,但我仍然得到了1/1/1900。