How to Use CASE Function in SQL

In this article I am going to explain how to use case function in SQL.
  • 2708

Introduction

In SQL Server there are two type of function which are used to manipulate data in database.

  • System define function
  • User define function

SQL server provide a list of system define function which are used to manipulate data. These system define function are predefine. We can't change functionality of these system define function. There are many situation where we need a function which performer some specific task according to our need. There function are known as user define function.

Case Function

Case function execute a sequence of statement depending upon condition. CASE function in SQL operates by comparing the first expression to the expression in each WHEN clause for equivalency. Expressions which  are equivalent in Case function, expression in the THEN clause will be executed.

Example

declare

@st_marks int,

@st_result varchar(15)

select @st_marks = 80

select @st_result =

case

when @st_marks>70 then 'A Grade'

when @st_marks<70 and @st_marks>=50 then 'B Grade'

when @st_marks < 50 then 'Fail'

end

print 'result = ' + @st_result


Output

Clipboard04.jpg


Categories

More Articles

© 2019 DotNetHeaven. All rights reserved.