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!