/// <summary> /// Permanently removes this column from the table. /// </summary> /// <remarks> /// If there are dependencies on this column other than a primary key or a default, the operation may fail. /// </remarks> public void Remove() { // Remove the primary key if this column is in it bool inPrimaryKey = this.ColumnInformation.Key; ArrayList keyColumns = new ArrayList(); if (inPrimaryKey) { NativeMethods.IKeys keys = Table.dmoTable.GetKeys(); for (int i = 0; i < keys.GetCount(); i++) { // Find the primary key if (keys.Item(i + 1).GetType() == NativeMethods.SQLDMO_KEY_TYPE.SQLDMOKey_Primary) { // First we have to keep a list of columns so we can undo the operation NativeMethods.INames columnNames = keys.Item(i + 1).GetKeyColumns(); for (int j = 0; j < columnNames.GetCount(); j++) { keyColumns.Add(columnNames.Item(j + 1)); } // Remove the primary key completely // NOTE: This is what SQL Server Enterprise Manager does keys.Remove(i + 1); break; } } } // Remove default string defaultValue = this.dmoColumn.GetDRIDefault().GetText(); this.dmoColumn.GetDRIDefault().Remove(); // Permanently delete this column try { dmoColumn.Remove(); } catch { // Undo operations and rethrow the exception // Set default back this.dmoColumn.GetDRIDefault().SetText(defaultValue); // If necessary, create primary key and add original columns to it if (inPrimaryKey) { NativeMethods.IKey primaryKey = (NativeMethods.IKey) new NativeMethods.Key(); primaryKey.SetType(NativeMethods.SQLDMO_KEY_TYPE.SQLDMOKey_Primary); NativeMethods.INames columnNames = primaryKey.GetKeyColumns(); for (int i = 0; i < keyColumns.Count; i++) { columnNames.Add(columnInfo.Name); } table.dmoTable.GetKeys().Add(primaryKey); } throw; } }