How to find tables in a Database in C#

A database refers to a structured collection of information, carefully organized to facilitate efficient retrieval. It encompasses interconnected tables consisting of rows and columns, wherein each table holds specific data elements. A table, in turn, represents a cohesive assembly of data, arranged in a format characterized by vertical columns and horizontal rows.

Number of tables present within a database

In certain scenarios, it becomes necessary to determine the number of tables present within a database. To accomplish this, one can rely on the system tables intrinsic to the SQL Server database. These system tables serve as repositories storing comprehensive details regarding the structure, metadata, and other pertinent information about the database. In these situations you can use the following SQL for finding how many tables in a database.

Select DISTINCT(name) FROM sys.Tables

Returns a row for each table object, currently only with sys.objects.type = U.

Full Source C#
using System; using System.Collections.Generic; using System; using System.Data; using System.Data.SqlClient; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string connetionString = null; SqlConnection connection; SqlCommand command; SqlDataAdapter adapter = new SqlDataAdapter(); DataSet ds = new DataSet(); int i = 0; string sql = null; connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"; sql = "Select DISTINCT(name) FROM sys.Tables"; connection = new SqlConnection(connetionString); try { connection.Open(); command = new SqlCommand(sql, connection); adapter.SelectCommand = command; adapter.Fill(ds); adapter.Dispose(); command.Dispose(); connection.Close(); for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++) { MessageBox.Show(ds.Tables[0].Rows[i].ItemArray[0].ToString()); } } catch (Exception ex) { MessageBox.Show("Can not open connection ! "); } } } }

Conclusion

Accessing the system tables and employing appropriate query techniques, one can effectively ascertain the precise count of tables existing within the SQL Server database. This knowledge is valuable for gaining insights into the overall database structure and facilitating further analysis, management, and utilization of the data contained within.