Last active
March 25, 2026 22:52
-
-
Save sunmeat/29c127d93656ad79024c74a934d26281 to your computer and use it in GitHub Desktop.
список таблиць певної БД, список назв полів з типами
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using Microsoft.Data.SqlClient; | |
| class Program | |
| { | |
| static void Main() | |
| { | |
| Console.Title = "Список таблиць БД"; | |
| Console.OutputEncoding = System.Text.Encoding.UTF8; | |
| // MARS - Multiple Active Result Sets !!! MultipleActiveResultSets=True; !!! | |
| // це спеціальна можливість SQL Server, яка дозволяє одночасно відкрити кілька активних читань (DataReader) на одному й тому ж з'єднанні | |
| string connectionString = "Server=localhost; Database=Store; Integrated Security=True; TrustServerCertificate=True; MultipleActiveResultSets=True;"; | |
| using (var connection = new SqlConnection(connectionString)) | |
| { | |
| try | |
| { | |
| connection.Open(); | |
| // отримуємо список таблиць у поточній базі даних | |
| var tablesQuery = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'"; | |
| var tables = new List<string>(); | |
| using (var tableCommand = new SqlCommand(tablesQuery, connection)) | |
| using (var reader = tableCommand.ExecuteReader()) | |
| { | |
| Console.WriteLine("Таблиці в базі даних:"); | |
| while (reader.Read()) | |
| { | |
| string tableName = reader.GetString(0); | |
| tables.Add(tableName); | |
| Console.WriteLine($"- {tableName}"); | |
| } | |
| } // reader автоматично закриється | |
| Console.WriteLine("\nДетальна інформація про поля таблиць:\n"); | |
| // для кожної таблиці виводимо список полів та їх типи даних | |
| foreach (var table in tables) | |
| { | |
| Console.WriteLine($"Таблиця: {table}"); | |
| string columnsQuery = @" | |
| SELECT COLUMN_NAME, DATA_TYPE | |
| FROM INFORMATION_SCHEMA.COLUMNS | |
| WHERE TABLE_NAME = @TableName"; | |
| using (var columnCommand = new SqlCommand(columnsQuery, connection)) | |
| { | |
| columnCommand.Parameters.AddWithValue("@TableName", table); | |
| using (var columnReader = columnCommand.ExecuteReader()) | |
| { | |
| while (columnReader.Read()) | |
| { | |
| string columnName = columnReader.GetString(0); | |
| string dataType = columnReader.GetString(1); | |
| Console.WriteLine($" - {columnName} ({dataType})"); | |
| } | |
| } | |
| } | |
| Console.WriteLine(); | |
| } | |
| } | |
| catch (Exception ex) | |
| { | |
| Console.WriteLine("Помилка: " + ex.Message); | |
| } | |
| } | |
| Console.ReadLine(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment