SQL C#

List All SQL Tables

This C# program demonstrates how to list all SQL tables in a database for Microsoft SQL in C#.

Program.cs

using System;
using System.Data.SqlClient;

namespace ListTables {
    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 sTableList = "";
                using (SqlCommand qCommand = new SqlCommand(
                        "SELECT * FROM information_schema.tables", qConnection)) {
                    using (SqlDataReader qReader = qCommand.ExecuteReader()) {
                        // Each row holds the properties of a table.
                        while (qReader.Read()) {
                            object[] qValues = new object[qReader.FieldCount];
                            qReader.GetValues(qValues);
                            foreach (object qValue in qValues) {
                                sTableList += qValue.ToString() + "   ";
                            }
                            sTableList += "\n";
                        }
                    }
                }
                Console.WriteLine(sTableList);
            }
        }
    }
}
 

Output

catholic   dbo   sacraments   BASE TABLE
catholic   dbo   apostles   BASE TABLE

Press any key to continue . . .
 

Tables

Tables
 
 

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