Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I perform a case-sensitive search and replace in SQL 2000/2005?

In order to perform a case-sensitive search/replace on a table in a SQL Server 2000/2005 database, you must use the correct collation.

How do you determine whether the default collation for a database is case-sensitive, and if it isn't, how to perform a case-sensitive search/replace?

like image 635
Andrew Myhre Avatar asked Sep 22 '08 09:09

Andrew Myhre


People also ask

Is replace in SQL case sensitive?

Note: The REPLACE function is case-insensitive in MS SQL Server.

How do you do a find and replace in SQL?

On the Edit menu, point to Find and Replace, and then click Quick Find to open the dialog box with find options, but without replace options. On the Edit menu, point to Find and Replace, and then click Quick Replace to open the dialog box with both find options and replace options.

How do you do a case insensitive search in SQL?

To do a case-insensitive comparison, use the ILIKE keyword; e.g., column ILIKE 'aBc' and column ILIKE 'ABC' both return TRUE for 'abc' . In contrast, MySQL and MS SQL Server have case-insensitive behaviors by default. This means WHERE column = 'abc' returns TRUE for e.g., 'abc' , 'ABC' , or 'aBc' .


2 Answers

SELECT testColumn FROM testTable  
    WHERE testColumn COLLATE Latin1_General_CS_AS = 'example' 

SELECT testColumn FROM testTable
    WHERE testColumn COLLATE Latin1_General_CS_AS = 'EXAMPLE' 

SELECT testColumn FROM testTable 
    WHERE testColumn COLLATE Latin1_General_CS_AS = 'eXaMpLe' 

Don't assume the default collation will be case sensitive, just specify a case sensitive one every time (using the correct one for your language of course)

like image 110
blowdart Avatar answered Oct 13 '22 13:10

blowdart


Determine whether the default collation is case-sensitive like this:

select charindex('RESULT', 'If the result is 0 you are in a case-sensitive collation mode')

A result of 0 indicates you are in a case-sensitive collation mode, 8 indicates it is case-insensitive.

If the collation is case-insensitive, you need to explicitly declare the collation mode you want to use when performing a search/replace.

Here's how to construct an UPDATE statement to perform a case-sensitive search/replace by specifying the collation mode to use:

update ContentTable
set ContentValue = replace(ContentValue COLLATE Latin1_General_BIN, 'THECONTENT', 'TheContent')
from StringResource
where charindex('THECONTENT', ContentValue COLLATE Latin1_General_BIN) > 0

This will match and replace 'THECONTENT', but not 'TheContent' or 'thecontent'.

like image 26
Andrew Myhre Avatar answered Oct 13 '22 11:10

Andrew Myhre