Click here to Skip to main content
Click here to Skip to main content

How To do Case Sensitive String Match in SQL Server

, 12 May 2014
Rate this:
Please Sign up or sign in to vote.
How to do case sensitive string match in SQL Server

Introduction

While working on a SP today, I noticed that SQL Server does a case-insensitive string match in a query. Hence in scenarios where passwords are to be validated, using a query as “WHERE Password =@Password” will give valid results if the user enters password as “admin” or “ADMIN” even though when the password is set as “aDmiN”. In this post, we will resolve this issue using a very simple method.

Let us consider below is our normal SQL procedure that validates a user from the tblUser table.

CREATE PROCEDURE [dbo].[tblUserSelect_Authenticate]
    @Username nvarchar(50),
    @Password nvarchar(50)
AS
BEGIN
    SELECT * FROM tblUser WHERE Username = @Username AND Password = @Password
END

To tell SQL do a case-sensitive search, we will modify the above procedure as below. Please note we added a “COLLATE SQL_Latin1_General_CP1_CS_AS” to the field we want an exact match for.

CREATE PROCEDURE [dbo].[tblUserSelect_Authenticate]
    @Username nvarchar(50),
    @Password nvarchar(50)
AS
BEGIN
     SELECT * FROM tblUser WHERE Username = @Username AND Password = @Password COLLATE SQL_Latin1_General_CP1_CS_AS
END

Keep learning and sharing! Cheers!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Nitesh Luharuka
Team Leader Independent IT Professional, Consultant
India India
An Independent IT Professional and Consultant on MS Technologies like .Net | MVC | Silverlight | Sharepoint | MS Project Server along with open source CMS Systems like DotNetNuke etc.
 
I am an enthusiastic technocrat who love to debug problems and solve them. I love writing articles on my website in my spare time. Please visit my Website for more details and subscribe to get technology related tips/tricks.
Follow on   Twitter   LinkedIn

Comments and Discussions

 
GeneralMy vote of 2 PinmemberRajesh Varma Buddaraju22-May-14 0:07 
QuestionPassword? Pinmemberdandy7212-May-14 13:58 
AnswerRe: Password? PinmemberNitesh Luharuka12-May-14 18:43 
GeneralRe: Password? Pinmemberdandy7213-May-14 2:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140721.1 | Last Updated 12 May 2014
Article Copyright 2014 by Nitesh Luharuka
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid