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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3969059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 07:59:21  来源:igfitidea点击:

SQL Case Sensitive String Compare

sqlsql-server

提问by amccormack

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'. I do not want this behaviour.

...将返回具有“K”属性的行。我不想要这种行为。

回答by amccormack

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

Did the trick.

做到了。

回答by Jugal

You can also convert that attribute as case sensitiveusing 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 insensitiveagain, then use

如果要再次使该列不区分大小写,请使用

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

回答by QMaster

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. 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.:

您可以轻松地将列转换为 VARBINARY(Max Length),长度必须是您期望的最大长度以避免有缺陷的比较,将长度设置为列长度就足够了。修剪列可帮助您比较实际值,除了空间在表列中具有含义和值外,这是一个简单示例,如您所见,我修剪了列值,然后进行了转换和比较。:

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

Hope this help.

希望这有帮助。

回答by Dave Sexton

Just as another alternative you could use HASHBYTES, something like this:

作为另一种选择,您可以使用 HASHBYTES,如下所示:

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

回答by MatTheCat

You can define attributeas BINARYor use INSTRor STRCMPto perform your search.

您可以定义attributeBINARY或使用INSTRSTRCMP执行您的搜索。