0

Let's say I have a table "foo" that I want to script out using SMO. Is there a way to have it so that in the generated script the table has a different name such as "foo2"?

Database db = sqlServer.Databases["testdb"];
Table foo = db.Tables["foo"];
foo.Name = "foo2";

If I do this, I get this exception when I try to set foo.Name:

"Cannot perform the operation on this object, because the object is a member of a collection."

Is there any way to do this with SMO?

3 Answers 3

1

For people like me who are trying to find out how to rename a column using SMO, if you're using the same method as above

foo.Name = "foo2";

you will get the same exception message in this thread. To rename the column you simply need to go

foo.Rename("foo2");

See MSDN for more details:

Sign up to request clarification or add additional context in comments.

Comments

0

You'll have to put the output of the Script method into a string variable and use Replace to substitute the name.

3 Comments

Seems risky since the table name might be a substring of other objects (columns, etc)
True, but can probably be worked around by FIND "CREATE TABLE foo" REPLACE "CREATE TABLE foo2" to avoid getting into the columns. But then you may have to do multiple replacements to get into constraints and indexes. Not sure if those are scripted separately. Been a while since I played with SMO.
The table name will be right after the first "CREATE TABLE " in the script.
0

You can create an in memory new table with the new name and then script that table.

You can find the code to copy table at Copying a table using SMO

Instead of calling the Create() on the new table, you need to simply call Script().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.