gpt4 book ai didi

sql - 如何使用正确的小数/$结果来转换计算列

转载 作者:行者123 更新时间:2023-12-03 02:05:53 25 4
gpt4 key购买 nike

我在 sql server 2008 中有以下计算列

[Total] AS  CAST ( ((val1/(1000)) * [val2]) AS DECIMAL(18,2))  PERSISTED,

当 val1 = 862500 且 val2 = 8 时,计算值 = 6896.00

我需要它是小数/金钱,其中 (862500/1000) * 8 = 6900.00(不是 6896.00)。

最佳答案

BOL 说:

Caution: When you use the +, -, *, /, or % arithmetic operators to perform implicit or explicit conversion of int, smallint, tinyint, or bigint constant values to the float, real, decimal or numeric data types, the rules that SQL Server applies when it calculates the data type and precision of the expression results differ depending on whether the query is autoparameterized or not.

Therefore, similar expressions in queries can sometimes produce different results. When a query is not autoparameterized, the constant value is first converted to numeric, whose precision is just large enough to hold the value of the constant, before converting to the specified data type. For example, the constant value 1 is converted to numeric (1, 0), and the constant value 250 is converted to numeric (3, 0).

When a query is autoparameterized, the constant value is always converted to numeric (10, 0) before converting to the final data type. When the / operator is involved, not only can the result type's precision differ among similar queries, but the result value can differ also. For example, the result value of an autoparameterized query that includes the expression SELECT CAST (1.0 / 7 AS float) will differ from the result value of the same query that is not autoparameterized, because the results of the autoparameterized query will be truncated to fit into the numeric (10, 0) data type. For more information about parameterized queries, see Simple Parameterization.

因此,需要将[val1]、1000和[val2]转换为float类型:

[Total] AS CAST ( ((CAST ([val1] as float)/CAST (1000 as float)) * CAST ([val2] as float)) AS DECIMAL(18,2)) PERSISTED

关于sql - 如何使用正确的小数/$结果来转换计算列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7802209/

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