我意识到,如果我的所有值都是固定宽度的,建议使用CHAR。但是,那又怎样?为了安全起见,为什么不为所有文本字段选择VARCHAR呢?


当前回答

当使用varchar值时,SQL Server每行需要额外的2个字节来存储关于该列的一些信息,而如果使用char则不需要 所以除非你

其他回答

我认为在你的情况下,可能没有理由不选择Varchar。它为您提供了灵活性,正如许多受访者所提到的,现在的性能是这样的,除非在非常特定的情况下,我们普通人(而不是谷歌DBA)不会注意到差异。

当谈到DB类型时,值得注意的一件有趣的事情是sqlite(一个非常受欢迎的迷你数据库,具有相当令人印象深刻的性能)将所有内容作为字符串放入数据库并动态地输入类型。

我总是使用VarChar,通常使它比我可能迫切需要的要大得多。如你所说,为了安全起见,为什么不买50英镑呢?

许多人指出,如果知道值的确切长度,使用CHAR会有一些好处。但是,虽然今天将美国州存储为CHAR(2)很棒,但当您从销售人员那里收到“我们刚刚完成了对澳大利亚的第一笔销售”的消息时,您将陷入痛苦的世界。我总是高估我认为字段需要多长时间,而不是做一个“准确”的猜测来覆盖未来的事件。VARCHAR将在这方面给我更多的灵活性。

当使用varchar值时,SQL Server每行需要额外的2个字节来存储关于该列的一些信息,而如果使用char则不需要 所以除非你

这是典型的空间与性能的权衡。

在MS SQL 2005中,Varchar(或每个字符需要两个字节的语言,如中文)是可变长度的。如果您在将行写入硬盘后再添加数据,则会将数据定位在与原始行不相邻的位置,并导致数据文件碎片化。这将影响性能。

所以,如果空间不是问题,那么Char格式的性能更好,但如果你想保持数据库的大小,那么varchars格式更好。

There are performance benefits, but here is one that has not been mentioned: row migration. With char, you reserve the entire space in advance.So let's says you have a char(1000), and you store 10 characters, you will use up all 1000 charaters of space. In a varchar2(1000), you will only use 10 characters. The problem comes when you modify the data. Let's say you update the column to now contain 900 characters. It is possible that the space to expand the varchar is not available in the current block. In that case, the DB engine must migrate the row to another block, and make a pointer in the original block to the new row in the new block. To read this data, the DB engine will now have to read 2 blocks. No one can equivocally say that varchar or char are better. There is a space for time tradeoff, and consideration of whether the data will be updated, especially if there is a good chance that it will grow.