为什么使用 CAST 时 VARCHAR 的默认长度是 30?
在 SQL Server 2005 中这个查询
select len(cast('the quick brown fox jumped over the lazy dog' as varchar))
返回 30 作为长度,而提供的字符串有更多字符.这似乎是默认设置.为什么是 30,而不是 32 或任何其他 2 的幂?
我知道在转换为 varchar 时我应该总是指定长度,但这是一个快速的让我们检查一下的查询.问题仍然存在,为什么是 30?
解决方案为什么不指定 varchar 长度?即:
SELECT CAST('敏捷的棕色狐狸跳过懒狗' AS VARCHAR(45))
至于为什么 30,这是 SQL Server 中该类型的默认长度.
来自 char 和 varchar (Transact-SQL):><块引用>
在数据定义或变量声明语句中未指定n时,默认长度为1.使用CAST和CONVERT函数时未指定n时,默认长度为30.
In SQL server 2005 this query
select len(cast('the quick brown fox jumped over the lazy dog' as varchar))
returns 30 as length while the supplied string has more characters. This seems to be the default. Why 30, and not 32 or any other power of 2?
[EDIT] I am aware that I should always specifiy the length when casting to varchar but this was a quick let's-check-something query. Questions remains, why 30?
解决方案Why don't you specify the varchar length? ie:
SELECT CAST('the quick brown fox jumped over the lazy dog' AS VARCHAR(45))
As far as why 30, that's the default length in SQL Server for that type.
From char and varchar (Transact-SQL):
When n is not specified in a data definition or variable declaration statement, the default length is 1. When n is not specified when using the CAST and CONVERT functions, the default length is 30.
相关文章