Monday, August 5, 2013

SQL Variables

It's been a while since the last time I blogged.  After a family reunion and a busy week at work, I've been slow to get back into the blogging side of life.

Today I've decided to start off with a subject that is rather easy.

In SQL, as with most programming languages, you will find something called a variable (it may be called something else in other programming languages).  A variable is a set of data that you give a name to and then can assign values to.  For example, in SQL you could have a variable called @pi (the @ symbol tells SQL that this is a variable) and assign it a value of 3.14.  If you need to use the 3.14 value throughout your program, you can then call @pi instead of 3.14 each time.

You might be thinking to yourself "why would I want to create/use a variable instead of just entering 3.14 every time I need it?"  Well, there are many ways to answer this question, but the best answer is that what would happen if you accidentally entered 3.15 in one instance instead of 3.14?  You could potentially throw off the rest of your program.  A variable allows you to use the same value over again without having to re-type it and therefore not leaving yourself open for mistakes.

There are two steps to creating variables:

  1. Declare the variable.  You have to let SQL know that the variable exists and give the variable a data type (int, varchar, datetime, etc.)
  2. Set a value to the variable.
So, if I wanted to create my @pi variable, I would do it like this:

DECLARE @pi numeric(5,2)
SET @pi = 3.14

You can also declare and set the variable on the same line:

DECLARE @pi numeric(5,2) = 3.14

We can then take that variable and use it:

@Circumference = 2 * @pi * radius

As you dive more into using variables, you will see they are quite useful.

To read more on SQL variables, go here: Local Variables

No comments:

Post a Comment