Thursday, January 20, 2011

Table variables and SQL Server

In a recent post, I mentioned temporary tables (you can find that post here). An alternative to temporary tables are table variables. Tablevariables are a lot like temporary tables, except the table variable has a few advantages over temporary tables:

  • 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
We declare table variables sort of like other variables, but the syntax looks like this:

DECLARE @<VariableName> TABLE
(
<COLUMNS>
);

Here is an example, using the Library database I created in an earlier post:

  1. USE Library
  2. DECLARE @SomeAuthors TABLE
  3. (
  4.     authorID INT
  5.     , first_Name VARCHAR(50)
  6. );

Here is a way we could use table variables:

  1. USE Library
  2. DECLARE @SomeAuthors TABLE
  3. (
  4.     author_ID INT
  5.     , first_Name VARCHAR(50)
  6. );
  7. INSERT INTO @SomeAuthors SELECT author_ID, first_Name
  8. FROM Authors WHERE first_Name = ' Geoffrey';
  9. UPDATE Authors SET Authors.last_Name = 'We updated this column'
  10. WHERE Authors.first_Name IN (SELECT first_Name FROM @SomeAuthors);
  11. 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.

1 comment:

I Break Code Where code gets done.
ASP.NET | HTML | SQL Server | VB.NET | Request A Topic |