SQL Server:数据类型“等级"在算术运算中? [英] SQL Server: data type "rank" in arithmetic operations?

查看:41
本文介绍了SQL Server:数据类型“等级"在算术运算中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当两个不同数据类型的值放在一起进行算术运算时,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:

  1. 用户定义的数据类型(最高)
  2. sql_variant
  3. xml
  4. 日期时间偏移
  5. 日期时间2
  6. 日期时间
  7. 小日期时间
  8. 日期
  9. 时间
  10. 浮动
  11. 真实
  12. 十进制
  13. 小钱
  14. bigint
  15. 内部
  16. smallint
  17. tinyint
  18. 文本
  19. 文字
  20. 图片
  21. 时间戳
  22. 唯一标识符
  23. nvarchar(包括 nvarchar(max) )
  24. nchar
  25. varchar(包括 varchar(max) )
  26. 字符
  27. varbinary(包括 varbinary(max) )
  28. 二进制(最低)

有关当两个操作数都是 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆