Declare yourself

Introduction to SQL Server

John MacKintosh

Instructor

Variables

SELECT * 
FROM artist 
WHERE name = 'AC/DC';

Now change the query for another artist:

SELECT * 
FROM artist 
WHERE name = 'U2';

To avoid repetition, create a variable:

SELECT * 
FROM artist 
WHERE name = @my_artist;
Introduction to SQL Server

DECLARE

DECLARE @

Integer variable:

DECLARE @test_int INT

Varchar variable:

DECLARE @my_artist VARCHAR(100)
Introduction to SQL Server

SET

Integer variable:

DECLARE @test_int INT

SET @test_int = 5

Assign value to @my_artist:

DECLARE @my_artist  varchar(100)

SET @my_artist = 'AC/DC'
Introduction to SQL Server
DECLARE @my_artist varchar(100)
DECLARE @my_album varchar(300);

SET @my_artist = 'AC/DC'
SET @my_album  = 'Let There Be Rock' ;

SELECT --
FROM --
WHERE artist = @my_artist
AND album = @my_album;
DECLARE @my_artist varchar(100)
DECLARE @my_album varchar(300);

SET @my_artist = 'U2'
SET @my_album  = 'Pop' ;

SELECT --
FROM --
WHERE artist = @my_artist
AND album = @my_album;
Introduction to SQL Server

Temporary tables

SELECT 
  col1, 
  col2, 
  col3 INTO #my_temp_table
FROM my_existing_table 
WHERE 
  -- Conditions
  • #my_temp_table exists until connection or session ends
-- Remove table manually
DROP TABLE #my_temp_table
Introduction to SQL Server

Let's declare some variables!

Introduction to SQL Server

Preparing Video For Download...