Friday, April 6, 2012

How to verify if two strings are equal in Sql?

This question might appear to you when you want to verify credentials for a user at login.
I found out that for SQL these two conditions will give the same result.
1. if(@Password = 'test')
2. if(@Password = 'test ')
(note the space)
So there is a problem.
I found out a simple solution for comparing these two strings. When you compare strings you have to hash them. So we are going to use Hashbytes function. Here you can find more details.
For our example we can verify like this:
if ( HASHBYTES('MD5', convert(nvarchar(50), @Password )) = HASHBYTES('MD5', 'test ' ))
will return expected result.
One think to note: it is important to keep in mind datatype. Datatypes must be the same otherwise you won't get the same hash. Md5 has in mind even data types when converting ;)

Hope will help you.

No comments:

Post a Comment