Being Sensitive in an Insensitive World

SQL Server allows you to set a case sensitive collation at both the database and column level but often you will need to do a case sensitive search when everything is case insensitive. Not to worry, you can set the collation directly in the query.

/*
To test string equality including case when the DB is 
not case sensitive you must 
include collation as part of the test as follows:
*/
 
 
declare @mystring1 varchar(10) 
declare @mystring2 varchar(10) 
set @mystring1 ='abc'
set @mystring2 ='ABC'
 
-- by default
if @mystring1 = @mystring2
                print 'match'
else
                print 'not a match'
                
-- by adding a case sensitive colation whe can check case
if @mystring1 = @mystring2 COLLATE Latin1_General_CS_AS
                print 'match'
else
                print 'not a match'
                
-- now make them equal in case and test again
set @mystring2 ='abc'
if @mystring1 = @mystring2 COLLATE Latin1_General_CS_AS
                print 'match'
else
                print 'not a match'
 
/*Here is a sample use */
use Northwind
go
select * from customers 
where companyname='alfreds futterkiste' -- works
 
select * from customers 
where companyname='alfreds futterkiste' COLLATE Latin1_General_CS_AS  --fails
 
select * from customers 
where companyname='Alfreds Futterkiste' COLLATE Latin1_General_CS_AS  --works
Technorati Tags: ,

posted @ Friday, July 03, 2009 10:43 PM

Print

Comments on this entry:

No comments posted yet.

Your comment:



 (will not be displayed)


 
 
 
 
 

Live Comment Preview:

 
«February»
SunMonTueWedThuFriSat
31123456
78910111213
14151617181920
21222324252627
28123456
78910111213