MySQL database with unique fields ignored ending spaces

后端 未结 4 413
别那么骄傲
别那么骄傲 2020-11-29 08:39

My projects requires to start inputs from the user with the spacing on the left and spacing on the right of a word, for example \'apple\'. If the user types in \' apple\' or

4条回答
  •  不知归路
    2020-11-29 09:35

    This is not about CHAR vs VARCHAR. SQL Server does not consider trailing spaces when it comes to string comparison, which is applied also when checking a unique key constraint. So it is not that you cannot insert value with trailing spaces, but once you insert, you cannot insert another value with more or fewer spaces.

    As a solution to your problem, you can add a column that keeps the length of the string, and make the length AND the string value as a composite unique key constraint.

    In SQL Server 2012, you can even make the length column as a computed column so that you don't have to worry about the value at all. See http://sqlfiddle.com/#!6/32e94 for an example with SQL Server 2012. (I bet something similar is possible in MySQL.)

提交回复
热议问题