Esistenza di una tabella nel database

by 1. luglio 2010 14.43

Ogni tanto c'è la necessità di sapere se sul database è presente una tabella oppure no. Con il seguente codice possiamo verificare facilmente se una tabella esiste. Il parametro da passare è comprensivo di schema, per esempio dbo.Anagrafiche.

In VB.NET:

Function TableExists(tableNameAndSchema As String) As Boolean
   Using connection As New SqlConnection(connectionString)
      Dim checkTable As String = [String].Format("IF OBJECT_ID('{0}', 'U') IS NOT NULL SELECT 'true' ELSE SELECT 'false'", tableNameAndSchema)
      Dim command As New SqlCommand(checkTable, connection)
      command.CommandType = CommandType.Text
      connection.Open()
 
      Return Convert.ToBoolean(command.ExecuteScalar())
   End Using
End Function

e anche in C#:

bool TableExists(string tableNameAndSchema){
   using (SqlConnection connection = new SqlConnection(connectionString))
   {     
     string checkTable = String.Format(
                         "IF OBJECT_ID('{0}', 'U') IS NOT NULL SELECT 'true' ELSE SELECT 'false'", tableNameAndSchema);
       SqlCommand command = new SqlCommand(checkTable, connection);
      command.CommandType = CommandType.Text;
      connection.Open();
 
      return Convert.ToBoolean(command.ExecuteScalar());   
   }
}

Ciao e buon lavoro!

Tags: , , , ,

Page List

Calendar

<<  febbraio 2012  >>
lumamegivesado
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

View posts in large calendar