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
答案 0 :(得分:5)
Money有4个小数位....它是一个定点数据类型。
答案 1 :(得分: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
答案 2 :(得分: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
答案 3 :(得分:0)
客户端正在格式化。 SQL Server SSMS或其他。 SQL Server在数据流中返回一个完整的货币值,它需要一个完整的8个字节。 (http://msdn.microsoft.com/en-us/library/cc448435.aspx)。如果您将SQL Server转换为varchar,则默认为2个小数位
请注意,Stack Overflow数据浏览器甚至没有显示相同的结果:
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