Thursday, March 17, 2011

Table Variables and Inner Joins

When we create and use table variables, we sometimes need to user inner joins on table variables. Well, thankfully, this is the same as joining two regular tables:

  1. USE master;
  2. GO
  3. -- Create our first table variable to hold user accounts.
  4. DECLARE @UserAccounts TABLE
  5. (
  6.     acountID INT
  7.     , firstName VARCHAR(50)
  8.     , lastName VARCHAR(50)
  9. );
  10. -- Create our second table variable to hold our user account passwords.
  11. DECLARE @Passwords TABLE
  12. (
  13.     acountID INT
  14.     , [password] VARCHAR(50)
  15. );
  16. -- Insert some records into our UserAccounts table variable.
  17. INSERT INTO @UserAccounts
  18. VALUES (1, 'John', 'Doe');
  19. INSERT INTO @UserAccounts
  20. VALUES (2, 'Jane', 'Doe');
  21. INSERT INTO @UserAccounts
  22. VALUES (3, 'Jim', 'Doe');
  23. -- Insert some records into our Passwords table variable.
  24. INSERT INTO @Passwords
  25. VALUES (1, 'password');
  26. INSERT INTO @Passwords
  27. VALUES (2, 'jane32');
  28. INSERT INTO @Passwords
  29. VALUES (3, 'Password!');
  30. -- Inner join between two table variables.
  31. SELECT U.firstName, U.lastName, P.[password]
  32. FROM @UserAccounts AS U
  33. INNER JOIN @Passwords AS P
  34. ON U.acountID = P.acountID;

The output of this query should be:


(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)
firstName                                          lastName                                           password
-------------------------------------------------- -------------------------------------------------- --------------------------------------------------
John                                               Doe                                                password
Jane                                               Doe                                                jane32
Jim                                                Doe                                                Password!

(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 |