Case-Sensitive Comparisons and Sorts on a Case-Insensitive Server

Despite the reason(s) you had for setting up your SQL Server
case-insensitive, you may occasionally need to do case-sensitive comparisons and
sorts. The varbinary data type can accomplish this. Here’s a simple table to
illustrate:

Click here for code example 1.

Say we want to look at codes that are all uppercase. We can’t do it
like this; this query will return all the rows:

select *
from vend
where v_code = upper(v_code)

Let’s rewrite it using varbinary:

Click here for code example 2.

“TraMi” can be distinguished from “TRAMI” with the following
query:

Click here for code example 3.

If you need to do this frequently, you can save some typing by adding a
computed column to the table.

alter table vend
add varb as cast(v_code as varbinary)
go

select v_code
from vend
where varb = cast('TraMi' as varbinary)

Computed columns can’t be indexed, at least in SQL Server 7.0, so you should
try to give the optimizer something to chew on. The server is very smart
and will pick a good plan without your help if usable indexes and statistics are
available, but it’s worthwhile to experiment and tweak with the Query Analyzer,
and perhaps even the Profiler.

Also, I’m using the default length for varbinary. See BOL. Either provide for
adequate size or risk subtle errors.

For the conclusion of our varbinary tour, let’s get a sorted,
case-sensitive list:

select v_code
from vend
group by varb, v_code
order by varb

Acknowledgement to Neil Pike’s FAQ.

Get the Free Newsletter!

Subscribe to Cloud Insider for top news, trends & analysis

Latest Articles