2011-09-01 67 views
4

SQL Server如何知道如何檢索這些值?SQL Server如何知道如何使用金錢

Key   someMoney 
----------- --------------------- 
1   5.00 
2   5.002 
3   5.0001 

基本上,我想知道如何知道有多少小數位沒有太多的性能影響。

我想

Key   someMoney    places 
----------- --------------------- ---------- 
1   5.00     2 
2   5.002     3 
3   5.0001    4 
+2

僅僅指剛爲貨幣數據類型不是一個非常準確的數據類型。如果你打算做任何類型的數據計算,你最好使用十進制。 – DForck42

+0

@ DForck42 - 謝謝,但我正在使用現有系統 –

回答

0

因此,這是一個巨大的醜陋的黑客攻擊,但它會給你你正在尋找...

DECLARE @TestValue MONEY 
SET @TestValue = 1.001 

DECLARE @TestString VARCHAR(50) 
SET @TestString = REPLACE(RTRIM(REPLACE(CONVERT(VARCHAR, CONVERT(DECIMAL(10,4), @TestValue)), '0', ' ')), ' ', '0') 

SELECT LEN(@TestString) - CHARINDEX('.', @TestString) AS Places 
1

這將產生的價值正確的結果,但我不確定它是否表現良好,我還沒有嘗試使用您列出的示例以外的數據:

; 
with money_cte ([Key], [someMoney]) 
as 
(
    select 1, cast(5.00 as money) 
    union 
    select 2, cast(5.002 as money) 
    union 
    select 3, cast(5.0001 as money) 
) 

select [Key], [someMoney], abs(floor(log10([someMoney] - round([someMoney], 0, 1)))) as places 
from money_cte 
where [someMoney] - round([someMoney], 0, 1) <> 0 

union 

select [Key], [someMoney], 2 as places 
from money_cte 
where [someMoney] - round([someMoney], 0, 1) = 0 
0

客戶端正在格式化它。 SQL Server SSMS或其他。 SQL Server在數據流中返回一個完整的貨幣值,它需要8個字節。 (http://msdn.microsoft.com/en-us/library/cc448435.aspx)。如果您有SQL服務器轉換爲varchar,則默認爲2位小數

注意,堆棧溢出數據瀏覽器甚至不顯示你有相同的結果:

http://data.stackexchange.com/stackoverflow/q/111288/

; 
with money_cte ([Key], [someMoney]) 
as 
(
    select 1, cast(5.00 as money) 
    union 
    select 2, cast(5.002 as money) 
    union 
    select 3, cast(5.0001 as money) 
) 

select * 
    , CONVERT(varchar, someMoney) AS varchar_version 
    , CONVERT(varchar, someMoney, 2) AS varchar_version2 
FROM money_cte​