2011-09-01 49 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​