SQL variable code example

Example 1: sql declare variable

-- Declare the variable to be used.
DECLARE @MyCounter int;

-- Initialize the variable.
SET @MyCounter = 0;

Example 2: how to declare a variable in sql

DECLARE @COURSE_ID AS INT, @COURSE_NAME VARCHAR (10);

Example 3: declare value in sql

DECLARE  { @LOCAL_VARIABLE[AS] data_type  [ = value ] }

Example 4: var in sql

One way of doing this is to use database variables

create table testcalc (
   id int(11) not null auto_increment,
   num1 int(11) default null,
   num2 int(11) default null,
   num3 int(11) default null,
   num4 int(11) default null,
   primary key(id)
);

insert into testcalc values
(default, 1, 2, 3, 4),
(default, 5, 10, 15, 20);
Then you can get the same results as in your example by storing the calculation results in variable syntax like this

@youVar := (calc) as resultName01
Then it will be available to following calculations to use like this

(@youVar + newCalc) as resultName02
We can apply it to your example like this

select
   id,
   num1,
   num2,
   num3,
   num4,
   @1plus2 := (num1 + num2) as 1plus2,                   # create var01
   @1plus2mult3 := (@1plus2 * num3) as 1plus2mult3,      # create var02 using var01
   @sumOfCalc := (@1plus2 + @1plus2mult3) as sumOfCalc   # create var03 using var01 and var02
from testcalc;

Example 5: variables in select statement in sql server

USE AdventureWorks2014;
GO
DECLARE @MyVariable int;
SET @MyVariable = 1;
-- Terminate the batch by using the GO keyword.
GO 
-- @MyVariable has gone out of scope and no longer exists.

-- This SELECT statement generates a syntax error because it is
-- no longer legal to reference @MyVariable.
SELECT BusinessEntityID, NationalIDNumber, JobTitle
FROM HumanResources.Employee
WHERE BusinessEntityID = @MyVariable;

Example 6: local variables in sql

Local variables:
These variables can be used or exist 
only inside the function. These variables
are not used or referred by any other function.

Global variables:
These variables are the variables which
can be accessed throughout the program.
Global variables cannot be created
whenever that function is called.

Tags:

Sql Example