SQL:比较字符串是否是 MD5 哈希?
问题:
我需要比较一个字符串是否是 SQL 中的 MD5 哈希值。
我发现了这个 PHP 函数:
function isValidMd5($md5)
{
return !empty($md5) && preg_match('/^[a-f0-9]{32}$/', $md5);
}
由于 SQL 缺少 {32} 语法,我只是重复 [a-f0-9] 32 次:
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
但是,为了避免与由 32 [af] 组成的用户名发生可能的冲突,尽管可能性不大,我想做类似的比较大写。
但如果出于测试目的我这样做:
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
我得到的是,而不是否。
但是 COLLATE Latin1_General_CS_AS 应该使其区分大小写......
如何使 IF 中的 LIKE 区分大小写?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最好通过检查任何导致检查失败的单一因素来反转检查并使其更易于维护。这意味着您不必在代码中重复
[0-9a-f]
32 次。即,如果它不是 32 个字符或者它包含十六进制集之外的字符,那么它会失败。
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.
这行得通吗?
Will this work?
好的,经过仔细检查问题,这是最好的解决方案:
请注意,重要的是要写 ABCDEF 而不是 AF,因为否则 A 和 F 之间的任何字母都不区分大小写。
(至于 AF:请注意,小“a”是边界大小写,因为它不在这个范围内,与小“b”不同。)
并且作为 MD5-Check 函数:
OK, after painstaking examination of the problem, this is the best solution:
Note that it's important to write ABCDEF instead of A-F, because else any letter in between A and F is not case-sensitive.
(as for A-F: note that little 'a' is a border-case, as it isn't in this range, unlike little 'b'.)
And as MD5-Checkfunction: