SQL Server:数据类型“等级"在算术运算中? [英] SQL Server: data type "rank" in arithmetic operations?
问题描述
当两个不同数据类型的值放在一起进行算术运算时,SQL Server 会自动将值转换为特定的数据类型.例如
When two values with different data types are put together for an arithmetic operation, SQL Server will convert values automatically into certain data type. E.g.
DECLARE @d NUMERIC(9,6);
SET @d = 1.0;
SELECT @d/3;
GO
结果 0.33333333.这种转换背后的内在逻辑是什么?数据类型之间是否存在某种等级"(转换将发生在哪个方向")?
results 0.33333333. What is the internal logic behind this conversion? Is there some "rank" between data types (into which "direction" the conversion will happen)?
推荐答案
请参阅:数据类型优先级(对于 SQL-Server 2000),位于 msdn.microsoft.com
See: Data Type Precedence (for SQL-Server 2000) at msdn.microsoft.com
来自 SQL-Server 2008 的同一页面:
当一个运算符将两个不同数据类型的表达式,数据类型优先规则指定数据类型较低的优先级被转换为具有较高优先级的数据类型.
When an operator combines two expressions of different data types, the rules for data type precedence specify that the data type with the lower precedence is converted to the data type with the higher precedence.
如果转换不是支持隐式转换,则返回一个错误.当两个操作数表达式具有相同的数据时类型,操作的结果有那个数据类型.
If the conversion is not a supported implicit conversion, an error is returned. When both operand expressions have the same data type, the result of the operation has that data type.
SQL Server 使用以下数据类型的优先顺序:
SQL Server uses the following precedence order for data types:
- 用户定义的数据类型(最高)
- sql_variant
- xml
- 日期时间偏移
- 日期时间2
- 日期时间
- 小日期时间
- 日期
- 时间
- 浮动
- 真实
- 十进制
- 钱
- 小钱
- bigint
- 内部
- smallint
- tinyint
- 位
- 文本
- 文字
- 图片
- 时间戳
- 唯一标识符
- nvarchar(包括 nvarchar(max) )
- nchar
- varchar(包括 varchar(max) )
- 字符
- varbinary(包括 varbinary(max) )
- 二进制(最低)
有关当两个操作数都是 char、varchar、binary 或 varbinary 表达式并连接或比较它们以及它们都是具有不同精度或小数位数的小数时的各种详细信息,请参阅:精度、比例和长度
For various details regarding when both operands are char, varchar, binary, or varbinary expressions and they are concatenated or compared and when they are both decimals with different precision or scale, see: Precision, Scale, and Length
以下 SO 问题/答案也相关:sql-server-truncates-decimal-points-of-a-newly-created-field-in-a-view
The following SO question/answer is also relevant: sql-server-truncates-decimal-points-of-a-newly-created-field-in-a-view
这篇关于SQL Server:数据类型“等级"在算术运算中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!