SQL C#

Check Table Existence

This C# program demonstrates how to check for the existence of an SQL table in a database for Microsoft SQL in C#.

Program.cs

using System;
using System.Data.SqlClient;

namespace CheckForTable {
    class Program {
        static void Main(string[] args) {
            // The using block ensures that the connection is closed when it exits this block.
            using (SqlConnection qConnection = new SqlConnection(
                    @"Server=localhost\SQLEXPRESS01;Database=catholic;Trusted_Connection=True;")) {
                qConnection.Open();
                string[] saTables = { "holy days", "saints", "sacraments", "virtues", "apostles"};
                // Run through the array of database names and check each one.
                foreach (string sTable in saTables) {
                    if (TableExists(qConnection, sTable)) {
                        Console.WriteLine("The table " + sTable + " exists.");
                    } else {
                        Console.WriteLine("The table " + sTable + " does not exist.");
                    }
                }
            }
        }

        public static bool TableExists(SqlConnection qConnection, string sTable) {
            using (var qCommand = new SqlCommand(
                @"SELECT count(*) as IsExists FROM dbo.sysobjects " + 
                "where id = object_id('[dbo].[" + sTable + "]')",
                qConnection)) {
                return ((int)qCommand.ExecuteScalar() == 1);
            }
        }
    }
}
 

Output

The table holy days does not exist.
The table saints does not exist.
The table sacraments exists.
The table virtues does not exist.
The table apostles exists.
Press any key to continue . . .
 

Tables

Tables
 
 

© 2007–2024 XoaX.net LLC. All rights reserved.