Pages

Monday, May 3, 2010

Select Multiple Table Columns with JOINS

In one of our project(a kind of ETL project), there was a requirement to map the a single table columns with multiple table column. I searched in many forums and finally from MSDN learned a new implementation using Joins.

Here we go:

These are the three tables and their columns.

MasterTable:
ID
Name
Value
Area
State
County
CreatedDate
ModifiedDate

State:
ID
StateCode
State
CreatedDate
ModifiedDate

Area:
ID
AreaCode
Area
CreatedDate
ModifiedDate

The Area and State tables are like KeyValue pair tables, in which the AreaCode and StateCode represents the integer value for corresponding string values. The requirement is to create a View for MasterTable, in which the Area should be matched with AreaCode, and State to be matched with StateCode.

Code Snippet:

CREATE VIEW [dbo].[vMaster]
AS
SELECT m.ID,
m.Name,
m.Value,
a.AreaCode,
s.StateCode,
m.County,
m.CreatedDate,
m.ModifiedDate

FROM MasterTable m LEFT JOIN Area a
ON a.Area = m.Area LEFT JOIN State s
ON s.State = m.State

I think this might be useful. Don't feel shy to drop in your comments.

Happy coding. Have a good day.

1 comment:

  1. Good one - SQL Views best illustrated with such an example

    ReplyDelete