Table Variable in SQL Server

The Table Variable in SQL Server stores a set of records like tables. And Table Variables are the best alternative to Temp Tables. Like Local Vars, this variable scope limited to User Defined Functions or Stored procedures.

The SQL Table variable is very fast when compared to temporary ones, and it is recommended to use this for less amount of data. The syntax of the Table variable is similar to the Create Statement.

    Column_Name1 Data_Type(Size) [NULL | NOT NULL],
    Column_Name2 Data_Type(Size) [NULL | NOT NULL],
    Column_NameN Data_Type(Size) [NULL | NOT NULL]

Create Sql Table Variable Example

Let us see how to Create a table variable in the Server, How to insert new records into it. And, how to select records from it.

TIP: You cannot use it as either Input or an Output Parameter.

  [CustomerKey] [int] IDENTITY(1,1) NOT NULL,
  [FirstName] [varchar](50) NULL,
  [LastName] [varchar](50) NULL,
  [BirthDate] [date] NULL,
  [EmailAddress] [nvarchar](50) NULL,
  [Yearly Income] [money] NULL,
  [Profession] [nvarchar](100) NULL
-- Inserting Values
VALUES ('Imran', 'Khan', '10-08-1985', '', 15900, 'Skilled Professional')
      ,('Doe', 'Lara', '10-08-1985', '', 15000, 'Management')
      ,('Ramesh', 'Kumar', '10-08-1985', '', 65000, 'Professional')

-- Selecting Values
SELECT * FROM @Records
Table Variable in SQL Server 1

We are executing all the statements together. Let me show you what happens when we run them independently.

There won’t be any problem to declare this!

Table Variable in SQL Server 2


Table Variable in SQL Server 3

NOTE: You don’t need any DELETE or DROP statement to drop this. Database Engine will automatically delete when it exits from the scope.

I hope you understood the scope of it. Please refer Temporary, User Defined FunctionsStored procedures, and Create Table.

Comments are closed.