Recently found when comparing strings in SQL Server if the end of the string is a space then SQL Server ignores those spaces and compares them directly to the usual string judgment logic in the program.
Declare @a nvarchar( -);Set @a=N'happycat1988' Declare @b nvarchar( -);Set @b=N'happycat1988' if(@a= @b) Select 'True' asDirect equals comparisonElse Select 'False' asDirect equals comparisonif(@a like @b) Select 'True' asLike comparisonElse Select 'False' asLike comparison
The results of the above query execution are as follows
Direct equals comparison -- ---- True (1 rows affected) like comparison -- ---- False (1 rows affected)
From the above can be seen when the direct equal judgement of the SQL will ignore the end of the space but like but can be the correct comparison although with a kind is also a method but if with a% and so may judge the error can not only use as a judge, but anyway, is to attach a condition Is there anything more simple than like? And then I thought about using the Len function with the string length comparison and then stepping on the other pit.
Declare @a nvarchar( -);Set @a=N'happycat1988' Declare @b nvarchar( -);Set @b=N'happycat1988' Select Len(@a)'Len of a',Len(@b)'Len of B',datalength(@a)'Datalength of a',datalength(@b)'Datalength of B'
The results of the above query execution are as follows
Len of a len of b datalengthofdatalength of b -- --------- ----------- --------------- --------------- a a - - (1 rows affected)
It is also possible to see that the Len function ignores the trailing spaces only by using the DATALENGTH function as the basis for additional precise judgments.
The description of the query for MSDN (Transact-SQL) Discovery Len function is "Returns the number of characters of the specified string expression, excluding Tra Iling Blanks. "That is to exclude the space comparison, so to swap with datalength
So we've sorted out some exact ways to judge strings.
Declare @a nvarchar( -);Set @a=N'happycat1988' Declare @b nvarchar( -);Set @b=N'happycat1988' if(@a = @b and datalength(@a)=datalength(@b)) Select 'True' asCompare with DatalengthElse Select 'False' asCompare with Datalengthif(@a = @b and @a like @b and @b like @a) Select 'True' asmatch like comparisonElse Select 'False' asmatch like comparisonif(@a + 'a' = @b + 'a') Select 'True' asEnd Supplemental Character comparisonElse Select 'False' asEnd Supplemental Character comparison
The results of the above query execution are as follows
Compare with Datalength -- ------------ False (1 rows affected) Mate like comparison -- ------ False (1 rows affected) end-of-complement character comparison -- ------ False (1 rows affected)
Hoping to help the same pit-stomping friends.
A hole in SQL Server that compares a string with a space at the end