Welcome on Business Intelligence Blog !!!
This blog is dedicated to Business Intelligence technologies under SAS9 and SQL Server 2005.
| Novembre 2009 | ||||||||||
| L | M | M | J | V | S | D | ||||
| 1 | ||||||||||
| 2 | 3 | 4 | 5 | 6 | 7 | 8 | ||||
| 9 | 10 | 11 | 12 | 13 | 14 | 15 | ||||
| 16 | 17 | 18 | 19 | 20 | 21 | 22 | ||||
| 23 | 24 | 25 | 26 | 27 | 28 | 29 | ||||
| 30 | ||||||||||
|
||||||||||
Toujours dans la série SMO, je souhaite maintenant créer un arbre objet qui me donnera pour une table,
sa clef (primaire ou composée), les tables qui dépendent de cette pk directement .
j'ai donc rajouté à mon objet TablePath une méthode AnalyseDatabaseBy :
132 public TablePath AnalyseDatabaseBy(string tableName,string schema)
133 {
134 /* Sets main information */
135 this.TableName = tableName;
136 this.Schema = schema;
137
138 /* Build a representation of any PrimaryKey */
139 ColumnCollection cols = _database.Tables[tableName, schema].Columns;
je fixe en passant le schema et le nom de la table en cours. (Mon idée derrière est de travailler par la suite récursif).
Deuxième étape : j'ai besoin de garder la ou les clefs de la tables via InPrimaryKey
Cette information ne se retrouve pas directement, il faut itérer dans les colonnes et "noter" les colonnes contributives, en testant InPrimaryKey :
138 /* Build a representation of any PrimaryKey */
139 ColumnCollection cols = _database.Tables[tableName, schema].Columns;
140 StringBuilder sb = new StringBuilder();
141 foreach (Column col in cols)
142 {
143 if (col.InPrimaryKey)
144 {
145 sb.Append("[");
146 sb.Append(col.Name);
147 sb.Append("]");
148 }
149 }
150 this._primaryKey = sb.ToString();
Troisième étape : trouver la liste des tables dépendantes via
EnumForeignKeys
J'ai caché toute cette logique sous la forme d'une fonction qui exploite la méthode EnumForeignKeys() d'objet
Table. Ci dessous la fin de la méthode AnalyseDatabaseBy () et l'appel à LookForChilds():
153 this._childs = this.lookForChilds(this);
154
155 return this;
156 }
158 private List<TablePath> lookForChilds( TablePath parent)
159 {
160 List<TablePath> ltp = new List<TablePath>();
161
162 DataTable dt = _database.Tables[parent.TableName,parent.Schema].EnumForeignKeys();
163 foreach (DataRow dr in dt.Rows)
164 {
165 TablePath tp = new TablePath();
166 tp._database = parent._database;
167 tp._server = parent._server;
168 tp.TableName = dr[1].ToString();
169 tp.Schema = dr[0].ToString();
170 ltp.Add(tp);
171 }
172 return ltp;
173 }
AnalyseDatabaseBy in action !
Appliqué dans notre IHM à
AdventureWorks et à la table SalesOrderDetails :
54 state = _tp.ConnectToDatabase(@".\BILAB2008","AdventureWorks",ServerAuthMode.Integrated,null,null);
55 _tp = _tp.AnalyseDatabaseBy("SalesOrderHeader","Sales");
Quickwatch du TablePath _tp :