tags:

views:

795

answers:

2

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?

A: 

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

John Mo
Seems risky since the table name might be a substring of other objects (columns, etc)
wnka
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.
John Mo
The table name will be right after the first "CREATE TABLE " in the script.
RBarryYoung
A: 

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().

Rashmi Pandit