Checking for and dropping an existing table via C# and SMO
Asked Answered
E

4

6

I am trying to look for a SQL table by name and if it exists drop it. This all needs to be done in C# using SMO.

To complicate it a bit more the table also has a schema other then "dbo".

Ultimatly the table will be recreated via SMO (I have this working) but I have to make sure it is not there before I can recreate it.

All of the examples that I have seen seem to be creating and then dropping the table all in the same context. In my case the table will have been created and populated in a previous session.

Elope answered 29/5, 2009 at 21:58 Comment(0)
N
0

First question is, why can you not drop and recreate with DDL?

And in answer to your question:

Table table = new Table(myDatabase, "MyTable", "MySchema");
Neisse answered 29/5, 2009 at 22:11 Comment(1)
Thank you for your answer. I have actually gone down the same route but different path: myTable.Schema = "MySchema" The table structure itself is determined on the fly by parsing an XML schema.Elope
S
12
var connection = new SqlConnection(connectionString);
var server = new Server(new ServerConnection(connection));

db = server.Databases["YourFavDB"];

db.Tables["YourHatedTable"].Drop();
Sparing answered 15/8, 2011 at 18:43 Comment(3)
The only one to answer the question and not a single upvote until now. Is there any justice on SO?Apothecium
There's no mention of schema here. It could be either completely reasonable, or dangerous to assume the schema is dbo, depending on your environmentRival
Good answer, I think DropIfExists() would be betterListlessness
F
4

I think the best approach would be:

Microsoft.SqlServer.Management.Smo.Database myDataBase = myServer.Databases["myDataBaseName"];
bool tableExists= myDataBase.Tables.Contains("myTable");
if (tableExists)
{
   myDataBase.Tables["myTable"].Drop();
}
Frager answered 12/8, 2014 at 20:31 Comment(1)
This should absolutely be the accepted answer to this question.Pyknic
E
1

Couldn't you just wrap your DROP TABLE statement in a try/catch block, and discard any errors that occur?

Anyway, the sql to determine if a table exists is:

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TableName]') AND type in (N'U'))
Enface answered 29/5, 2009 at 22:14 Comment(2)
It goes against my grain to use errors for program flow control. Thanks for the response.Elope
Well, couldn't you use the IF EXISTS I provided to check first, if you don't like the Try/Catch?Enface
N
0

First question is, why can you not drop and recreate with DDL?

And in answer to your question:

Table table = new Table(myDatabase, "MyTable", "MySchema");
Neisse answered 29/5, 2009 at 22:11 Comment(1)
Thank you for your answer. I have actually gone down the same route but different path: myTable.Schema = "MySchema" The table structure itself is determined on the fly by parsing an XML schema.Elope

© 2022 - 2024 — McMap. All rights reserved.