What are the use cases for selecting CHAR over VAR

2019-01-04 04:45发布

I realize that CHAR is recommended if all my values are fixed-width. But, so what? Why not just pick VARCHAR for all text fields just to be safe.

19条回答
一纸荒年 Trace。
2楼-- · 2019-01-04 05:51

Using CHAR (NCHAR) and VARCHAR (NVARCHAR) brings differences in the ways the database server stores the data. The first one introduces trailing blanks; I have encountered problem when using it with LIKE operator in SQL SERVER functions. So I have to make it safe by using VARCHAR (NVARCHAR) all the times.

For example, if we have a table TEST(ID INT, Status CHAR(1)), and you write a function to list all the records with some specific value like the following:

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

In this function we expect that when we put the default parameter the function will return all the rows, but in fact it does not. Change the @Status data type to VARCHAR will fix the issue.

查看更多
登录 后发表回答