2011-12-17 56 views
4

執行這些並檢查結果爲什麼是這樣?強制轉換爲Integer無法正常工作?

declare @a decimal(8,3) =235.363 
declare @b int   =1 

select case @b 
      when 1 then cast(@a as int) 
      when 2 then CAST(@a as decimal(8,3)) 
end 

Result : 235.000 

declare @a decimal(8,3) =235.363 
declare @b int   =1 

select case @b 
      when 1 then cast(@a as int) 
      --when 2 then CAST(@a as decimal(8,3)) 
end 

Result : 235 

declare @a decimal(8,3) =235.363 
declare @b int   =1 

select case @b 
      when 1 then cast(@a as tinyint) 
      when 2 then CAST(@a as float) 
end 

Result : 235 
+2

嗯,問題是:你在期待什麼? – 2011-12-17 09:06:29

回答

0

大概投操作會施放的所有選項,以更大的類型。

從MSDN:

的數據類型input_expression和每個when_expression必須 相同或必須是隱式轉換。

http://msdn.microsoft.com/en-us/library/ms181765.aspx

+0

它如何檢查更大的類型? – Nighil 2011-12-17 07:05:31

+0

select case @b 1 then then cast(@a as tinyint) 2 then CAST(@a as float) end ok那麼這是怎麼回事? – Nighil 2011-12-17 07:32:33

+0

float優先級是10 tiny int是18然後tinyint作爲輸出 – Nighil 2011-12-17 07:36:25

0

鑄造到整數無法正常工作。

您的陳述不正確!

CASE語句,可以只返回一個類型的數據,所以要根據你的說法,你可以返回INTdecimal(8,3),因爲你的case語句具有decimal(8,3)所以這裏INT數據隱式轉換爲十進制! 請看下面的例子:,總是試圖在CASE聲明中使用相同的返回類型來獲得正確和預期的結果,謝謝。

1.

select case @b 
    when 1 then CAST(@a as int) -- return type INT 
when 2 then CAST(@a as int) -- return type INT 
end 

2.

select case @b 
    when 1 then CAST(@a as int) -- return type INT and then converted to decimal(8,3) 
when 2 then CAST(@a as decimal(8,3)) -- return type return type INT 
end 
2

你看到的是不是你所得到的。

對於列時,SQL Server拾取正確的,更廣泛的類型(float超過tinyintdecimal超過int)。你可以通過做select into而不是僅僅選擇來驗證。

這只是不同的顯示規則。
當選定的列類型爲float時,如果沒有小數部分,則看不到尾部.000
對於設置了明確位置的decimal,如decimal(8,3),即使沒有小數部分,也會看到尾部.000。如果刪除說明符並僅將decimal作爲列類型,則.000將消失。

所有這些都不會影響實際的列類型,它始終是最寬的列類型。

2

此行爲the BOL entry for CASE

返回類型

返回從類型集合的優先級最高的類型 result_expressions和可選else_result_expression記錄。有關更多 的信息,請參閱Data Type Precedence (Transact-SQL)

如果按照鏈接數據類型的優先級,你會看到float的優先級高於decimal這反過來的優先級高於tinyint所以這是正常現象。

相關問題