I have an application which needs to use the MODEL database (This is
created by me and it acts as a template) to synchronize the tables,
stored procedures, triggers, indexes across multiple client database.
Basically, if there is a structural change to the MODEL database the
client databases need to be updated. For example, If I create a new
table or alter a table or modify a stored procedure or modify an index
the client databases need to be updated when I run the sync routine.
So far I have managed to create/drop tables, create/drop columns, create/drop stored procedures and create/drop triggers.
I need to be able to drop all relationships (constraints) and indexes
and recreate them. I need to know how this can be done using SMO. I can
do it using TSQL but I want to know if there is an alternative.
Thanks in advance.I figured it out ...
#Region " Relationships "
Private Sub DropRelationships(ByVal db As Database)
For Each tbl As Table In db.Tables
If tbl.ForeignKeys.Count > 0 Then
For Each key As ForeignKey In tbl.ForeignKeys
key.MarkForDrop(True)
Next
tbl.Alter()
End If
Next
End Sub
Private Sub CreateRelationships(ByVal AlterDB As Database, ByVal ModelDB As Database)
For Each tbl As Table In ModelDB.Tables
If tbl.ForeignKeys.Count > 0 Then
For Each key As ForeignKey In tbl.ForeignKeys
For Each col As ForeignKeyColumn In key.Columns
Dim rc As Column
Dim fk As ForeignKey
fk = New ForeignKey(AlterDB.Tables(tbl.Name), key.Name)
For Each c As Column In AlterDB.Tables(key.ReferencedTable).Columns
If c.InPrimaryKey Then
rc = c
End If
Next
Dim fkc As ForeignKeyColumn
fkc = New ForeignKeyColumn(fk, col.Name, rc.Name)
fk.Columns.Add(fkc)
fk.ReferencedTable = key.ReferencedTable
fk.ReferencedTableSchema = key.ReferencedTableSchema
fk.Create()
Next
Next
End If
Next
End Sub
#End Regionsql
No comments:
Post a Comment