1

I have a database that uses codes. Each code can be anywhere from two characters to ten characters long.

In MS SQL Server, is it better for performance to use char(10) for these codes and RTRIM them as they come in, or should I use varchar(10) and not have to worry about trimming the extra whitespace? I need to get rid of the whitespace because the codes will then be used in application logic for comparisons and what not.

As for the average code length, hard to tell exactly. Assume all codes are a random length between one and ten. Edit: A rough estimation is about 4.7 characters for the average length of a code.

4

5 回答 5

6

I'd vote for varchar.

I say varchar to avoid the TRIM which would invalidate index usage (unless you use a computed column etc which defeats the purpose, no?).

Otherwise at length 10, it would be 50/50 but TRIM tips the balance towards varchar and wins out over the fixed length benefit

于 2010-04-15T18:56:43.163 回答
3

作为一般规则,始终倾向于使用较小的存储空间而不是额外的 CPU。因为数据库性能的驱动因素始终是 IO,较小的数据记录意味着每页有更多的记录,这反过来意味着更少的 IO 请求。处理可变长度所涉及的额外 CPU 不会成为一个因素。从历史上看,在 80 年代甚至 90 年代的黑暗时代,这可能是一个可衡量的因素,但今天只是噪音。因为 CPU 和内存访问量大幅增加,但 IO 速度几乎保持不变。这就是为什么“旧书”建议在今天不适用的原因。除非您有像 char(2) 或类似的常量字段,否则请始终使用 varchar。

于 2010-04-15T20:17:01.223 回答
2

我相信您将无法分辨两者之间的速度差异。

于 2010-04-15T19:05:15.583 回答
1

您的要求是需要使用 varchar 的人的教科书定义。

如果您想担心性能,请担心 DB 设计和编写好的 SQL。数据库供应商对 Char 与 VarChar 内部进行了很好的优化。

于 2010-04-15T19:02:40.937 回答
0

在一本旧书中,我读到通常 char 是一个更好的选择,因为对于大多数记录,实际字符串长度至少是最大值的 60%;在您的示例中 - 如果所有记录中有一半以上的长度为 6 或更大。否则,请使用 varchar。

于 2010-04-15T19:02:16.197 回答