简体   繁体   English

SQL 区分大小写的字符串比较

[英]SQL Case Sensitive String Compare

How do you compare strings so that the comparison is true only if the cases of each of the strings are equal as well.您如何比较字符串,以便仅当每个字符串的情况也相等时比较才为真。 For example:例如:

Select * from a_table where attribute = 'k'

...will return a row with an attribute of 'K'. ...将返回具有“K”属性的行。 I do not want this behaviour.我不想要这种行为。

Select * from a_table where attribute = 'k' COLLATE Latin1_General_CS_AS 

做到了。

You can also convert that attribute as case sensitive using this syntax :您还可以使用以下语法将该属性转换为区分大小写

ALTER TABLE Table1
ALTER COLUMN Column1 VARCHAR(200)
COLLATE SQL_Latin1_General_CP1_CS_AS

Now your search will be case sensitive .现在您的搜索将区分大小写

If you want to make that column case insensitive again, then use如果要再次使该列不区分大小写,请使用

ALTER TABLE Table1
ALTER COLUMN Column1 VARCHAR(200)
COLLATE SQL_Latin1_General_CP1_CI_AS

You Can easily Convert columns to VARBINARY(Max Length), The length must be the maximum you expect to avoid defective comparison, It's enough to set length as the column length.您可以轻松地将列转换为 VARBINARY(Max Length),长度必须是您期望的最大长度以避免有缺陷的比较,将长度设置为列长度就足够了。 Trim column help you to compare the real value except space has a meaning and valued in your table columns, This is a simple sample and as you can see I Trim the columns value and then convert and compare.:修剪列可帮助您比较实际值,除了空间在表列中具有含义和值外,这是一个简单示例,正如您所看到的,我修剪列值,然后进行转换和比较。:

CONVERT(VARBINARY(250),LTRIM(RTRIM(Column1))) = CONVERT(VARBINARY(250),LTRIM(RTRIM(Column2)))

Hope this help.希望这有帮助。

Just as another alternative you could use HASHBYTES, something like this:作为另一种选择,您可以使用 HASHBYTES,如下所示:

SELECT * 
FROM a_table 
WHERE HASHBYTES('sha1', attribute) = HASHBYTES('sha1', 'k')

simplifying the general answer简化一般答案

SQL Case Sensitive String Compare SQL 区分大小写的字符串比较

These examples may be helpful:这些示例可能会有所帮助:

Declare @S1 varchar(20) = 'SQL'
Declare @S2 varchar(20) = 'sql'

  
if @S1 = @S2 print 'equal!' else print 'NOT equal!' -- equal (default non-case sensitivity for SQL

if cast(@S1 as binary) = cast(Upper(@S2) as binary) print 'equal!' else print 'NOT equal!' -- equal

if cast(@S1 as binary) = cast(@S2 as binary) print 'equal!' else print 'NOT equal!' -- not equal

if  @S1 COLLATE Latin1_General_CS_AS  = Upper(@S2) COLLATE Latin1_General_CS_AS  print 'equal!' else print 'NOT equal!' -- equal

if  @S1 COLLATE Latin1_General_CS_AS  = @S2 COLLATE Latin1_General_CS_AS  print 'equal!' else print 'NOT equal!' -- not equal

 

The convert is probably more efficient than something like runtime calculation of hashbytes, and I'd expect the collate may be even faster.转换可能比哈希字节的运行时计算更有效,我希望整理可能更快。

您可以将attribute定义为BINARY或使用INSTRSTRCMP来执行搜索。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM