Just like temporary tables, we have table variables in SQL. It is an alternative to temporary tables. If you’re using temporary tables and don’t need transactions on those tables and want better performance then use table variables instead of temporary tables.
Syntax
- DECLARE @Student TABLE
- (
- StudentIdint NOT NULL,
- StudentName varchar,
- Marks int
- )
Example of Table variable.
Copy the below script and execute in the SQL Server.
- DECLARE @Student TABLE
- (
- StudentIdint NOT NULL,
- StudentNamevarchar(20),
- Marks int
- )
- Insert Into @Student (StudentID,StudentName,Marks) Values (1,'Nitin Tyagi',200)
- Insert Into @Student (StudentID,StudentName,Marks) Values (2,'Amar Singh',400)
- Insert Into @Student (StudentID,StudentName,Marks) Values (3,'Vicky',300)
- Select * from @Student

When we create a table variable it only resides in memory which means it’s much faster. A table variable goes out of scope immediately after the batch ends just like regular variables go out of scope. This means we don’t have to explicitly drop them at the end of scripts.
Table variable can only have indexes that are automatically created with PRIMARY KEY & UNIQUE constraints as part of the DECLARE statement. We can also return a table variable from a user-defined function.
This is how we can use table variables in SQL Server.

GokulPosted Jun 23, 2016, 3:15 AM
Thanks for sharing