2014-03-28 62 views
2

我正在使用不同值的表對SQL視圖進行操作。我試圖將表中的兩列組合在一個以'/'分隔的視圖的單列中顯示。在SQL表中創建視圖的NULL值的問題

例如,我有兩列在名爲IninVolume與值表「在」是 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 

什麼更好的辦法來解決這個問題?

+1

'ISNULL(鑄造(在爲varchar(99)), '(null或空)')'? –

+1

NULL將吸收您連接的任何其他值,同樣的方法將任何數字乘以0將始終返回0.使用ISNULL可以根據Daniel E.建議的空字符串或「NULL」字符串替換空值。 –

+1

您需要使用'ISNULL'或'COALESCE'。 – Andrew

回答

1

替換此:

cast(outVolume as varchar(99)) 

白衣這樣的:

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

在每一個領域。希望這個幫助。

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)') 
1

ù本身IsNull以啓用可爲空的列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