在sql表中创建视图时出现NULL值问题

时间:2014-03-28 15:34:58

标签: sql sql-server

我正在使用不同值的表上的SQL视图。我正在尝试将表中的两列组合显示在由' /'分隔的视图的单个列中。

例如,我在名为IninVolume的表格中有两列,其值为' In'存在  1,2,NULL

和' inVolume'正在

NULL, 100, 200

我期待的结果是1/(NULL or Empty)2/100, (NULL or Empty)/200但是当我创建视图并运行它时,结果是 (NULL or Empty), 2/100, (NULL or Empty) 。问题是,如果表中的任何列In或inVolume为NULL,则视图中的列为NULL。

我创建了以下视图

SQL查看

CREATE VIEW [dbo].[Result]
AS

with CTE as(
SELECT distinct
   CC.Product,
   CC.Term,   
   CC.TermID,
   iCC.In,
   iCC.Out,
   iCC.inVolume,
   iCC.outVolume

   FROM Cust CC
CROSS APPLY (SELECT TOP 3
                In,
                Out, 
               inVolume,
                outVolume

             FROM Cust iCC
             WHERE CC.Term = iCC.Term and CC.Product = iCC.Product
             ORDER BY iCC.In DESC, iCC.Out ASC) iCC)
             select Product, Term, cast(inVolume as varchar(99)) + '/' + cast(In as varchar(99)) as value, inlabel as label from CTE 
             union
             select Product, Term, cast(Out as varchar(99)) + '/' + cast(outVolume as varchar(99)), outlabel from CTE 

GO

有什么更好的方法可以解决这个问题吗?

3 个答案:

答案 0 :(得分:1)

替换它:

cast(outVolume as varchar(99))

有了这个:

cast((CASE WHEN outVolume IS NULL THEN 0 ELSE outVolume END) as varchar(99))

在每个领域。希望这有帮助。

答案 1 :(得分:1)

替换

cast(inVolume as varchar(99)) + '/' + cast(In as varchar(99))` 

cast(inVolume as varchar(99)) + '/' 
+ ISNULL(cast(In as varchar(99)), '(NULL OR EMPTY)')`

cast(Out as varchar(99)) + '/' + cast(outVolume as varchar(99))` 

cast(Out as varchar(99)) + '/' 
+ ISNULL(cast(outVolume as varchar(99)), '(NULL OR EMPTY)')

答案 2 :(得分:1)

使用IsNull启用nullable-column concatentation

select Product, Term, 
IsNull(inVolume, '(NULL OR EMPTY)', cast(inVolume as varchar(99))) + '/' + 
IsNull(In, '(NULL OR EMPTY)', cast(In as varchar(99))) as value, 
inlabel as label from CTE 

UNION

select Product, Term, 
IsNull(Out, '(NULL OR EMPTY)', cast(Out as varchar(99))) + '/' + 
IsNull(outVolume, '(NULL OR EMPTY)', cast(outVolume as varchar(99))), 
outlabel from CTE