2012-12-05 120 views
4

我是SQL Server的新手,遇到問題。將SQL列空值轉換爲0

我有這個視圖,其中公式中的某些列允許爲空。

如何將這些空值轉換爲0,因爲如果它們爲空,則公式的結果也將爲空。

謝謝!

CREATE VIEW vwAchizitii 
AS 
    SELECT 
      ac_id 
      ,[Company] 
      ,No 
      ,[ContractID] 
      ,[Seller] 
      ,[AcquistionDate] 
      ,[Village] 
      ,[Commune] 
      ,[Area] 
      ,[PlotArea] 
      ,[FieldNo] 
      ,[Topo1] 
      ,[Topo2] 
      ,[Topo3] 
      ,[Topo4] 
      ,[Topo5] 
      ,[TotalAreaSqm] 
      ,[OwnershipTitle] 
      ,[CadastralNO] 
      ,[Type] 
      ,[Price] 
      ,[NotaryCosts] 
      ,[LandTax] 
      ,[OtherTaxes] 
      ,[AgentFee] 
      ,[CadastralFee] 
      ,[TabulationFee] 
      ,[CertSarcini] 
      ,[ProcuraNO] 
      ,(price+notarycosts+landtax+othertaxes+agentfee+cadastralfee+tabulationfee+certsarcini) as TotalCosts 
      ,(price+notarycosts+landtax+othertaxes+agentfee+cadastralfee+tabulationfee+certsarcini)/(TotalAreaSqm/10000) as RonPerHa 
      ,(price+notarycosts+landtax+othertaxes+agentfee+cadastralfee+tabulationfee+certsarcini)/(TotalAreaSqm/10000*FixHist) as EurPerHa 
      ,[DeclImpunere] 
      ,[FixHist] 
      ,(price+notarycosts+landtax+othertaxes+agentfee+cadastralfee+tabulationfee+certsarcini)/FixHist as EurHist 
      ,[LandStatus] 
FROM  
    nbAchizitii 
+0

從查看['ISNULL'](http://msdn.microsoft.com/zh-cn/library/ms184325.aspx)函數開始。 – vcsjones

+1

使用'ISNULL'或'COALESCE()'函數。 –

+0

這是爲什麼標記的.NET? – Paparazzi

回答

7

您可以使用ISNULL (Transact-SQL)

(isnull(price,0)+isnull(notarycosts,0)) as Total 
+0

非常感謝,我現在就試試! – user1820705

+0

你知道我如何設定公式結果的小數位數? – user1820705

+0

@ user1820705:看看[十進制和數字](http://msdn.microsoft.com/en-us/library/ms187746.aspx)例如。如果你需要兩位小數'CAST(50/10 AS decimal(5,2))' –

5

試試這個:

ISNULL([nullable field], 0) 
+0

謝謝你的幫助! – user1820705

10

嗯,有人應該放在一個字ANSI標準:

coalesce(<column>, 0) 

isNULL是特定於數據庫(甚至在一些數據庫中做不同的事情)。

+0

謝謝你親切的先生!但應該注意的是,對於簡單的單值操作,IsNull是MS SQL Server 2中速度較快的。 – hajikelist

+1

@hajikelist。 。 。對於* simple *操作,'isnull()'和'coalesce()'應該幾乎相同。當第一個參數很複雜時,'isnull()'更快。但是對於列引用它們應該是相同的。 –

+0

MySQL COALESCE()函數返回列表的第一個非空值 – user674669