Question:
I need to COMPARE if a string is a MD5 Hash in SQL.
I found this PHP-function:
function isValidMd5($md5)
{
return !empty($md5) && preg_match('/^[a-f0-9]{32}$/', $md5);
}
Since SQL lacks the {32} syntax, I just duplicate [a-f0-9] 32 times:
IF '200ceb26807d6bf99fd6f4f0d1ca54d4' LIKE '[a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9]'
BEGIN
PRINT 'YES'
END
ELSE
BEGIN
PRINT 'NO'
END
However, to avoid a possible collision with a username consisting of 32 [a-f], however unlikely, I want to do the like comparison uppercase.
But if for testing purposes I do:
IF 'E' COLLATE Latin1_General_CS_AS LIKE ('[a-f0-9]' COLLATE Latin1_General_CS_AS )
BEGIN
PRINT 'yes'
END
ELSE
BEGIN
PRINT 'no'
END
I get yes, and not no.
However COLLATE Latin1_General_CS_AS should make it case-sensitive…
How can a make the LIKE in this IF case-sensitive ?
Better to invert the check and make it simpler to maintain by checking for any single thing that will make it fail. This means you don’t have to repeat
[0-9a-f]32 times in the code.i.e., if it’s not 32 chars OR it contains a character outside the hexadecimal set then it fails.