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
- )
We can insert records in the table variables just like temporary tables. Select, Update, and delete also works with the table variable. In table variables the constraint types allowed are PRIMARY KEY, UNIQUE, NULL, and CHECK but they must be incorporated with the creation of the table in the DECLARE statement. FOREIGN KEY constraints are not allowed.
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
Following is the output we get when the preceding script is executed.
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.