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, Table variable scope limited to User Defined Functions or Stored procedures.
The SQL Table variable is very fast when compared to temporary tables, and it is recommended to use this for less amount of data. The syntax of the Table variable is similar to the Create Table Statement.
DECLARE @Table_Variable_Name TABLE ( 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 SQL 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.
DECLARE @TempTableVariable TABLE ( [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 INSERT INTO @TempTableVariable VALUES ('Imran', 'Khan', '10-08-1985', '[email protected]', 15900, 'Skilled Professional') ,('Doe', 'Lara', '10-08-1985', '[email protected]', 15000, 'Management') ,('Ramesh', 'Kumar', '10-08-1985', '[email protected]', 65000, 'Professional') -- Selecting Values SELECT * FROM @TempTableVariable
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!
NOTE: You don’t need any DELETE or DROP statement to drop this. Database Engine will automatically delete when it exits from the scope.