0

Simple Case Statements in SQL

Posted by Danielle Smith on 16:51 in
Good afternoon guys! Hope you're all well. Over the next few days - I will be working more on my development side of things (ASP.NET and C#) so I thought that this would be the ideal opportunity to run some smaller blogs on Simple Case Statements and some SQL Code Flow commands that you will most certainly come across.

Before I begin...

You must note that CASE statements are not used to control the execution flow of your transaction statements. Instead, it evaluates all conditions sequentially and stops when the first condition is satisfied, similarly to a switch case in other programming languages. The only difference is that you don't actually use the SWITCH keyword.

A simple CASE statement only allows 1 equality check, and it will pick the first satisfied condition before breaking out of the CASE statement and moving on. If none of your conditions are satisfied, it will look for an ELSE clause. Make sure you don't forget to declare your ELSE clause, otherwise it will just return NULL (and most of the time you wouldn't want to return that). Also, you must always remember finish your CASE statement with an END clause, otherwise you will receive the following error message:



Simple CASE Statement Example

Below is a quick and simple example of a CASE statement syntax within a SELECT statement:











Of course, there are lots of other places you can use them, however they tend to work as a searchable CASE statement rather than a simple CASE statement.

What Next...

Tomorrow, I will be writing about searchable CASE statements, which are slightly more complex. Thanks for reading today's blog post! If you have any questions/comments/feedback, please leave them in the comments section below and I will get back to you as soon as I can. Alternatively, please like my SQL Genius Facebook Page and leave a message on there. Many Thanks!

0 Comments

Post a Comment

Please post any feedback or comments here...

Copyright © 2009 SQL Genius - Personal Development of a Junior All rights reserved. Theme by Laptop Geek. | Bloggerized by FalconHive.