vbdotnet.it

Tricks & tips, workaround, forum and ideas with .Net

About the author

Enrico Rossini è il gestore di questo blog.
E-mail me Send mail

Recent posts

Recent comments

Contributi

Best 6 ~ 6 users ~ 6 comments

Info legali

Le opinioni espresse in questo blog sono strettamente personali e ogni persona è responsabile dei commenti che inserisce. I marchi citati sono delle rispettive aziende.

© Copyright 2010

Advertising


Esistenza di una tabella nel database

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!

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by enrico on Thursday, July 01, 2010 3:43 PM
Permalink | Comments (0) | Post RSSRSS comment feed