Wednesday, March 16, 2011

Inserting Records With Table Variables

In a previous post, located here, I talked about using table variables with SQL Server. This post will show the basic insertion of records into a table variable we will created called "UserAccounts". The fields will be "firstName" and "lastName". Then, we will select all the records from our table variable.

  1. USE master;
  2. GO
  3. -- The creation of our Table Variable.
  4. DECLARE @UserAccounts TABLE
  5. (
  6.     firstName VARCHAR(50)
  7.     , lastName VARCHAR(50)
  8. );
  9. -- Inserting 3 records into our Table Variable.
  10. INSERT INTO @UserAccounts
  11. VALUES ('John', 'Doe');
  12. INSERT INTO @UserAccounts
  13. VALUES ('Jane', 'Doe');
  14. INSERT INTO @UserAccounts
  15. VALUES ('Jim', 'Doe');
  16. -- Selecting the records from our Table Variable.
  17. SELECT * FROM @UserAccounts;

The output of running this query should be:



(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

firstName                                          lastName
-------------------------------------------------- --------------------------------------------------
John                                               Doe
Jane                                               Doe
Jim                                                Doe

(3 row(s) affected)

No comments:

Post a Comment

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