A basic Full Outer Join return all records from all tables, regardless of any matches. If there is not match, the join will return a 'null' value.
Here is an example of a full outer join:
- USE master;
- GO
- -- Create our first table variable to hold user accounts.
- DECLARE @UserAccounts TABLE
- (
- acountID INT
- , firstName VARCHAR(50)
- , lastName VARCHAR(50)
- );
- -- Create our second table variable to hold our user account passwords.
- DECLARE @Passwords TABLE
- (
- acountID INT
- , [password] VARCHAR(50)
- );
- -- Insert some records into our UserAccounts table variable.
- INSERT INTO @UserAccounts
- VALUES (1, 'John', 'Doe');
- INSERT INTO @UserAccounts
- VALUES (2, 'Jane', 'Doe');
- INSERT INTO @UserAccounts
- VALUES (3, 'Jim', 'Doe');
- INSERT INTO @UserAccounts
- VALUES (4, 'Jimmy', 'Doe');
- INSERT INTO @UserAccounts
- VALUES (5, 'Fonda', 'Doe');
- -- Insert some records into our Passwords table variable.
- INSERT INTO @Passwords
- VALUES (1, 'password');
- INSERT INTO @Passwords
- VALUES (2, 'jane32');
- INSERT INTO @Passwords
- VALUES (3, 'Password!');
- INSERT INTO @Passwords
- VALUES (10, 'bad password!');
- -- Full outer join between two table variables.
- SELECT U.firstName, U.lastName, P.[password]
- FROM @UserAccounts AS U FULL OUTER JOIN @Passwords AS P
- ON U.acountID = P.acountID;
This query returns this result:
(1 row(s) affected)
(1 row(s) affected)
(1 row(s) affected)
(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!
Jimmy Doe NULL
Fonda Doe NULL
NULL NULL bad password!
(6 row(s) affected)
No comments:
Post a Comment