- Table variables usually use fewer resources than a temporary table, which makes it a little bit faster
- Table variables will not exist after the procedure that called it exits, so there is no clean-up required with DROP statements like temporary tables
- USE Library
- DECLARE @SomeAuthors TABLE
- (
- authorID INT
- , first_Name VARCHAR(50)
- );
Here is a way we could use table variables:
- USE Library
- DECLARE @SomeAuthors TABLE
- (
- author_ID INT
- , first_Name VARCHAR(50)
- );
- INSERT INTO @SomeAuthors SELECT author_ID, first_Name
- FROM Authors WHERE first_Name = ' Geoffrey';
- UPDATE Authors SET Authors.last_Name = 'We updated this column'
- WHERE Authors.first_Name IN (SELECT first_Name FROM @SomeAuthors);
- SELECT * FROM Authors;
What this is doing is created a table variable called "SomeAuthors" and it is going to take the records from the Authors table in our Library database and put them into our SomeAuthors temporary variable. Then this little script is going to update all our records in the Authors table based on what is in the SomeAuthors variable. This can be expanded to do some rather cool things when we need to update records. The final line is just there to return the records of the Authors table to see what our script has done.