Database Journal
MS SQL Oracle DB2 Access MySQL PostgreSQL Sybase PHP SQL Etc SQL Scripts & Samples Links Database Forum

» Database Journal Home
» Database Articles
» Database Tutorials
MS SQL
Oracle
DB2
MS Access
MySQL
» RESOURCES
Database Tools
SQL Scripts & Samples
Links
» Database Forum
» Sitemap
Free Newsletters:
DatabaseDaily  
News Via RSS Feed


follow us on Twitter
Database Journal |DBA Support |SQLCourse |SQLCourse2
 

Featured Database Articles

MS SQL

Posted Mar 1, 2001

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

By Michael Trachtenberg

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.



MS SQL Archives

Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 




Latest Forum Threads
MS SQL Forum
Topic By Replies Updated
SQL 2005: SSIS: Error using SQL Server credentials poverty 3 August 17th, 07:43 AM
Need help changing table contents nkawtg 1 August 17th, 03:02 AM
SQL Server Memory confifuration bhosalenarayan 2 August 14th, 05:33 AM
SQL Server Primary Key and a Unique Key katty.jonh 2 July 25th, 10:36 AM


















Thanks for your registration, follow us on our social networks to keep up-to-date