Michael Cole (invalid (AT) microsoft (DOT) com) writes:
Quote:
I would like to create a view, that would return the following: -
ID Data1 Data2 Col1 Col2
1 A B G H
2 C D I P
3 E F Q Null
In other words, link to the data for Col1 and Col2 based off a
determination of the table and field from the table ZColumns.
Are there any thoughts as to how this could be done? |
WITH pivotedZ AS (
SELECT ID,
MIN(CASE ColumnID WHEN 1 THEN [Table] END) AS Table1,
MIN(CASE ColumnID WHEN 1 THEN [Column] END) AS Col1,
MIN(CASE ColumnID WHEN 2 THEN [Table] END) AS Table2,
MIN(CASE ColumnID WHEN 2 THEN [Column] END) AS Col2
FROM ZColumns
GROUP BY ID
)
SELECT Z.ID, D.Data1, D.Data2,
CASE WHEN Z.Table1 = '00001' AND Z.Col1 = '001' THEN T1.[001]
WHEN Z.Table1 = '00001' AND Z.Col1 = '002' THEN T1.[002]
WHEN Z.Table1 = '00002' AND Z.Col1 = '001' THEN T2.[001]
WHEN Z.Table1 = '00002' AND Z.Col1 = '002' THEN T2.[002]
END AS Col1,
CASE WHEN Z.Table2 = '00001' AND Z.Col2 = '001' THEN T1.[001]
WHEN Z.Table2 = '00001' AND Z.Col2 = '002' THEN T1.[002]
WHEN Z.Table2 = '00002' AND Z.Col2 = '001' THEN T2.[001]
WHEN Z.Table2 = '00002' AND Z.Col2 = '002' THEN T2.[002]
END AS Col2
FROM pivotedZ Z
LEFT JOIN ZData D ON Z.ID = D.ID
LEFT JOIN ZTab00001 T1 ON Z.ID = T1.ID
LEFT JOIN ZTab00002 T2 ON Z.ID = T2.ID
And if you tell me that you have umpteen of these ZTab000x tables,
I can you only wish you good luck. Bad database designs often leads
very difficult where you get lost in a morass of dynamic SQL.
--
Erland Sommarskog, SQL Server MVP, esquel (AT) sommarskog (DOT) se
Links for SQL Server Books Online:
SQL 2008: http://msdn.microsoft.com/en-us/sqlserver/cc514207.aspx
SQL 2005: http://msdn.microsoft.com/en-us/sqlserver/bb895970.aspx