Applying a Collation 让sql server 对大小写敏感

本文介绍如何在SQL Server中创建大小写敏感的查询及视图。通过指定SQL_Latin1_General_CP1_CS_AS排序规则,可以在已有的数据库中实现特定字段的大小写敏感搜索。文中提供了一个具体示例,展示了如何应用这一特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

sql server 默认安装时(SQL_Latin1_General_CP1_CI_AS )是不区分大小写的,可以在安装时选择排序规则时使用SQL_Latin1_General_CP1_CS_AS ,如果系统已经安装好了,又不想修改数

据库,仅想在查询时是对大小写敏感可以这样写

select * from Production.Productwhere name='Abc' COLLATE SQL_Latin1_General_CP1_CS_AS

在视图里

CREATE VIEW

Production.ProductSensitive

AS

SELECT

ProductID,

Name,

Name COLLATE SQL_Latin1_General_CP1_CS_AS AS NameSensitive

FROM Production.Product;

/************************************************************************************************************/


The following code creates a view that returns the ProductID column, and two versions of the Name column from the AdventureWorks.Production.Product table. The first Name column is left to the same collation as the source column, but the second Name column (aliased as NameSensitive) specifies a case sensitive collation for the column in the view.


USE AdventureWorks;

GO

CREATE VIEW

Production.ProductSensitive

AS

SELECT

ProductID,

Name,

Name COLLATE SQL_Latin1_General_CP1_CS_AS AS NameSensitive

FROM Production.Product;

The key piece is the line:


Name COLLATE SQL_Latin1_General_CP1_CS_AS AS NameSensitive

Most database developers know collations can be applied to databases and columns, but many don’t realize that we can apply collations to expressions as well. That is exactly what we are doing in that line. We are applying the case sensitive collation SQL_Latin1_General_CP1_CS_AS to the expression in the select list.

After running the code above to make the view, we can test that it works correctly by running the following statements:


--Should match at least one row. The [Name] column

--is not case sensitive

SELECT * FROM Production.ProductSensitive

WHERE Name='awc logo cap';

--Won't match any rows because [NameSensitive] is

--case sensitive

SELECT * FROM Production.ProductSensitive

WHERE NameSensitive='awc logo cap';

--Will match rows because [NameSensitive] is

--case sensitive, and the 'AWC Logo Cap' literal

--uses the proper case.

SELECT * FROM Production.ProductSensitive

WHERE NameSensitive='AWC Logo Cap';

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值