Why the SQL Server ignore the empty space at the end automatically?

爷,独闯天下 提交于 2019-12-28 04:18:19

问题


I wrote a query

SELECT * FROM Users WHERE UserName = 'admin '

by mistaken typing. But I found that the result is as the same as

SELECT * FROM Users WHERE UserName = 'admin'

It seems that the empty space at the end is ignored by SQL Server automatically.

Can anybody tell me why?

FYI, the column UserName is of type nvarchar(MAX).


回答1:


SQL Server is following the ANSI/ISO standard for string comparison.

The article How SQL Server Compares Strings with Trailing Spaces explains this in detail.

SQL Server follows the ANSI/ISO SQL-92 specification... on how to compare strings with spaces. The ANSI standard requires padding for the character strings used in comparisons so that their lengths match before comparing them. The padding directly affects the semantics of WHERE and HAVING clause predicates and other Transact-SQL string comparisons. For example, Transact-SQL considers the strings 'abc' and 'abc ' to be equivalent for most comparison operations.

Also, as explained in the article, if you compare with LIKE you do not get this behaviour.




回答2:


If you are trying like this

SELECT * 
FROM Users 
WHERE UserName = 'admin '

empty spaces are ignored SQL Server. But if you try like this

SELECT * 
FROM Users 
WHERE UserName Like 'admin '

It consider the empty spaces also.

DECLARE @Person1 varchar(50)='admin'
SELECT 1  WHERE @Person1 = 'admin '
SELECT 1  WHERE @Person1 like 'admin '

The result of the above query set is



来源:https://stackoverflow.com/questions/17876478/why-the-sql-server-ignore-the-empty-space-at-the-end-automatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!