gpt4 book ai didi

java - JDBC SQL Server 十进制 "invented"精度

转载 作者:行者123 更新时间:2023-12-02 11:34:07 25 4
gpt4 key购买 nike

注意:这可以与 SQL Server、Oracle、DB2 或 MySQL 数据库一起运行。但对于本示例,我仅使用 SQL Server。不过,该解决方案需要足够通用才能应用所有提到的数据库。

在 SQL Server 中,我有一列定义为 decimal(32, 16),因为该列必须能够存储潜在的大值或精确值。但是,它也可能存储较小或不精确的值。但是当我选择 BigDecimal 时,它会返回原始中没有的尾随零。我认为这是因为我的列定义允许高精度。

我不希望以“发明的”比例/精度存储或返回任何值,但我仍然需要考虑到那么大的比例/精度。

// ... set up ... 
// precision 2, scale 2
BigDecimal bdInsert = new BigDecimal("0.51");
preparedStatement.insertBigDecimal(1, bdInsert);
// ... insert/commit ... select ...
// precision 0, scale 16 <-- Grrrrrrr!
BigDecimal bdResult = resultSet.getBigDecimal(1);
System.out.println(bdResult);
// prints "0.5100000000000000" <-- Grrrrrrr!

SQL Server 是否不存储或 JDBC 不发送或选择插入的 BigDecimal 的精度和小数位数?

我不能直接截断零,因为 BigDecimal 可能存储有尾随零以表明它是精确的。

// "0.510000" indicating that this value is accurate to the 6th place
BigDecimal bdPrecise = new BigDecimal("0.510000");
preparedStatement.insertBigDecimal(1, bdPrecise);

// precision 0, scale 16
BigDecimal bdResult = resultSet.getBigDecimal(1);

System.out.println(bdResult);
// prints "0.5100000000000000" loses information

System.out.println(bdResult.stripTrailingZeros());
// prints "0.51", loses information

// What I want is "0.510000"

有没有办法通过 SQL Server 或 JDBC 来获取原始 BigDecimal 的小数位数/精度?

请不要告诉我我必须创建一个单独的列来存储这些信息...

我想另一种选择是只插入/选择 BigDecimals 作为字符串,然后从字符串中解析它,如 new BigDecimal(val) 。但我更喜欢存储为小数。

谢谢。

最佳答案

以下代码演示了 SQL Server 中的sql_variant 数据类型。 (以及如何显示有关表达式的数据类型信息。)由于该解决方案需要应用于任何能够保存位的,它不会解决您的所有问题,但它可能具有一定的值(value)。

我怀疑跨“所有”平台工作的唯一解决方案是字符串,可能包含具有明确精度的 XML。

declare @Samples as Table ( Value sql_variant );
insert into @Samples ( Value ) values
( Cast( 3.14 as Decimal( 10, 2 ) ) );
insert into @Samples ( Value ) values
( Cast( 3.14 as Decimal( 10, 3 ) ) );
insert into @Samples ( Value ) values
( Cast( 3.14 as Decimal( 10, 4 ) ) );
insert into @Samples ( Value ) values
-- NB: Both values are inserted with scale 5 when they are included in a single INSERT.
( Cast( 42 as Decimal( 10, 1 ) ) ),
( Cast( 42 as Decimal( 10, 5 ) ) );
insert into @Samples ( Value ) values
( Cast( 1.618 as Decimal( 10, 6 ) ) );
insert into @Samples ( Value ) values
( 'Edgar' );

select Value, SQL_Variant_Property( Value, 'BaseType' ) as BaseType,
SQL_Variant_Property( Value, 'Precision' ) as Precision,
SQL_Variant_Property( Value, 'Scale' ) as Scale
from @Samples;

(然后是钢厂,他们希望在英寸和十六分之一之间有一个点,例如 23 3/4 英寸显示为“23.12”。将“36.1”和“36.10”处理为输入时相差 9/16和输出?哦。)

关于java - JDBC SQL Server 十进制 "invented"精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49073362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com