T-SQL用空字符串替换空值

时间:2014-01-28 13:26:14

标签: 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,但是用户询问我是否可以从报表中删除空值并将结果保留为空字符串(如果适用)。完成此任务的最佳方法是什么?谢谢。!

2 个答案:

答案 0 :(得分:0)

您可以使用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关键字。如果您需要提供特定的日期格式,还可以将CAST更改为CONVERT

答案 1 :(得分:0)

试试这个:

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
相关问题