1

I have a database in sql server which is having few tables in it.

I need to populate a listbox which contains a list of tables names from the database which contains a specified column name say 'special' .

i have tried something like..

using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                List<string> tables = new List<string>();
                DataTable dt = connection.GetSchema("Tables");
                foreach (DataRow row in dt.Rows)
                {
                    string tablename = (string)row[2];
                    tables.Add(tablename);
                }
                listbox1.ItemsSource = tables;


                connection.Close();
            }

but it is showing all the tables present in the database..

but i want only those table which have a specific columns in a list...

Kindly suggest me the way ... :)

Vivek Saurav
  • 2,235
  • 4
  • 25
  • 46

3 Answers3

3

You can use this linq query (now tested):

List<string> tNames= new List<string>();  // fill it with some table names
List<string> columnNames = new List<string>() { "special" };
// ...

IEnumerable<DataRow> tableRows = con.GetSchema("Tables").AsEnumerable()
  .Where(r => tNames.Contains(r.Field<string>("TABLE_NAME"), StringComparer.OrdinalIgnoreCase));
foreach (DataRow tableRow in tableRows)
{
    String database = tableRow.Field<String>("TABLE_CATALOG");
    String schema = tableRow.Field<String>("TABLE_SCHEMA");
    String tableName = tableRow.Field<String>("TABLE_NAME");
    String tableType = tableRow.Field<String>("TABLE_TYPE");
    IEnumerable<DataRow> columns = con.GetSchema("Columns", new[] { database, null, tableName }).AsEnumerable()
        .Where(r => columnNames.Contains(r.Field<string>("COLUMN_NAME"), StringComparer.OrdinalIgnoreCase));
    if (columns.Any())
    {
        tables.Add(tableName);
    }
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
3

IMHO you should simply query the INFORMATION_SCHEMA.COLUMNS table instead of trying to filter the returned schema. First retrieving the hole schema to just throw most of the data away is totally ineffective.

SELECT c.TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS c
WHERE c.COLUMN_NAME = 'YourLovelyColumnName'
Ralf
  • 1,216
  • 10
  • 20
0

Assuming you are working on SQL Server:

IF COL_LENGTH('table_name','column_name') IS NOT NULL
 BEGIN
 /*Column exists */
 END

See more:

How to check if column exists in SQL Server table

Community
  • 1
  • 1
Sadique
  • 22,572
  • 7
  • 65
  • 91