Home >Database >Mysql Tutorial >How to Perform Case-Sensitive Searches in SQL Server WHERE Clauses?

How to Perform Case-Sensitive Searches in SQL Server WHERE Clauses?

Susan Sarandon
Susan SarandonOriginal
2025-01-14 09:05:42987browse

How to Perform Case-Sensitive Searches in SQL Server WHERE Clauses?

Achieving Case-Sensitive Searches in SQL Server WHERE Clauses

SQL Server's default behavior for string comparisons within WHERE clauses is case-insensitive. This presents a challenge when precise, case-sensitive searches are required.

Leveraging Collation for Case-Sensitive Comparisons

The solution lies in utilizing the COLLATE keyword. This keyword allows you to specify the collation for the column involved in the comparison, thereby defining the rules for string matching, including case sensitivity.

For instance:

<code class="language-sql">SELECT 1
FROM dbo.Customers
WHERE CustID COLLATE SQL_Latin1_General_CP1_CS_AS = @CustID
AND OrderID COLLATE SQL_Latin1_General_CP1_CS_AS = @OrderID</code>

Here, COLLATE SQL_Latin1_General_CP1_CS_AS enforces case-sensitive comparison on both CustID and OrderID columns.

Modifying Column Properties for Permanent Case Sensitivity

For consistent case-sensitive behavior, you can adjust the column properties directly within the table definition. By default, columns are created with case-insensitive properties.

Integrating COLLATE with the LIKE Operator

The COLLATE keyword seamlessly integrates with the LIKE operator for case-sensitive pattern matching:

<code class="language-sql">SELECT *
FROM tbl_Partners
WHERE PartnerName COLLATE SQL_Latin1_General_CP1_CS_AS LIKE 'MyEx%' COLLATE SQL_Latin1_General_CP1_CS_AS</code>

This query performs a case-sensitive search for PartnerName values starting with 'MyEx'.

The above is the detailed content of How to Perform Case-Sensitive Searches in SQL Server WHERE Clauses?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn