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


当前回答

使用CHAR (NCHAR)和VARCHAR (NVARCHAR)会在数据库服务器存储数据的方式上带来不同。第一个引入了尾随空格;我在SQL SERVER函数中使用LIKE操作符时遇到了问题。因此,我必须始终使用VARCHAR (NVARCHAR)来确保它的安全性。

例如,如果我们有一个表TEST(ID INT, Status CHAR(1)),你写一个函数列出所有具有特定值的记录,如下所示:

CREATE FUNCTION List(@Status AS CHAR(1) = '')
RETURNS TABLE
AS
RETURN
SELECT * FROM TEST
WHERE Status LIKE '%' + @Status '%'

在这个函数中,我们期望当我们输入默认参数时,函数会返回所有的行,但实际上并没有。将@Status数据类型更改为VARCHAR将解决该问题。

其他回答

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.

我会选择varchar,除非列存储固定的值,如美国州代码-这总是2个字符长,有效的美国州代码列表不经常改变:)。

在其他情况下,甚至像存储哈希密码(固定长度),我会选择varchar。

为什么——char类型的列总是用空格填充,这使得列my_column定义为char(5),值为'ABC'在比较中:

my_column = 'ABC' -- my_column stores 'ABC  ' value which is different then 'ABC'

假的。

这个特性可能会在开发过程中导致许多恼人的bug,并使测试更加困难。

使用CHAR (NCHAR)和VARCHAR (NVARCHAR)会在数据库服务器存储数据的方式上带来不同。第一个引入了尾随空格;我在SQL SERVER函数中使用LIKE操作符时遇到了问题。因此,我必须始终使用VARCHAR (NVARCHAR)来确保它的安全性。

例如,如果我们有一个表TEST(ID INT, Status CHAR(1)),你写一个函数列出所有具有特定值的记录,如下所示:

CREATE FUNCTION List(@Status AS CHAR(1) = '')
RETURNS TABLE
AS
RETURN
SELECT * FROM TEST
WHERE Status LIKE '%' + @Status '%'

在这个函数中,我们期望当我们输入默认参数时,函数会返回所有的行,但实际上并没有。将@Status数据类型更改为VARCHAR将解决该问题。

Char更快一点,所以如果你知道一个列有一定的长度,就使用Char。例如,存储(M)ale/(F)emale/(U)nknown表示性别,或者存储2个字符表示美国的一个州。

除了性能方面的好处外,CHAR还可以用来表示所有值都应该是相同的长度,例如,美国州缩写的列。