4

I'm trying to use Where statement for retrieving data from the database and it's always returning data if whitespaces are added at the end of the string, so

.Where(p => p.Username == "sysadmin")

and

.Where(p => p.Username == "sysadmin      ")

both are returning data (I expect the second one to return null). And the same thing is with WebSecurity.Login method, it is logging in succesfully in both cases.

Just code
  • 13,553
  • 10
  • 51
  • 93
Gab
  • 471
  • 3
  • 10
  • 25

1 Answers1

4

The reason why it is doing like that is:

SQL Server follows the ANSI/ISO SQL-92 specification (Section 8.2, , General rules #3) 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.

The only exception to this rule is the LIKE predicate. When the right side of a LIKE predicate expression features a value with a trailing space, SQL Server does not pad the two values to the same length before the comparison occurs. Because the purpose of the LIKE predicate, by definition, is to facilitate pattern searches rather than simple string equality tests, this does not violate the section of the ANSI SQL-92 specification mentioned earlier.

You can try to do as:

.Where(p => p.Username.Trim() == "sysadmin")
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • A little more info about the `.Trim()` method and its conversion to SQL: [link](http://stackoverflow.com/a/17424594/261050) – Maarten Jan 22 '16 at 10:23