Link to home
Start Free TrialLog in
Avatar of MiloDCooper
MiloDCooperFlag for United States of America

asked on

How do rename and remove columns in a MS SQL table?

I'm using the Server Management Objects library to alter a table.

My code for adding a column works fine, but whenever I try to rename a column, I get "SetName failed for Column '[columnName]'."

Likewise, my attempts to remove a column are met with "The Column '[columnName]' does not exist on the server."

All I'm doing are:

      tbl.Columns[oldName].Name = newName;

      tbl.Columns.Remove(name);

Another error that I've gotten when I attempt to remove columns is "You cannot perform operation Remove on an object in state Existing."

Help!
Avatar of sammySeltzer
sammySeltzer
Flag of United States of America image

Hi,

If all you want is to remove a column name from a table, why not simply do this:

ALTER TABLE TableName
DROP COLUMN ColumnName
And if your intention is to rename a column from old to new, for instance, this will do it:

sp_RENAME Yourtable.OldName', 'NewName' , 'COLUMN'

That's it
Is it possible that I misunderstood what you are trying to do?
ASKER CERTIFIED SOLUTION
Avatar of MiloDCooper
MiloDCooper
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of MiloDCooper

ASKER

Aaaaaaaaand I've found that renaming is achieved like so:

      tbl.Columns[oldName].Rename(newName);

K, so, never mind I guess.