I am developing some code to tabulate the datatable names and their corresponding columns from a database. I want to have the list that I can see on the MS SQL Report Builder - Query Designer:
Here's my code:
SqlConnection conn = new SqlConnection("Data Source = server; Initial catalog = Catalog; Integrated Security = true");
conn.Open();
DataTable dt = conn.GetSchema("Tables");
List<string> tablenames = new List<string>();
foreach(DataRow dr in dt.Rows){
string table = (string)dr[2];
if((string)dr[1] == "dbo"){
//Creating a list of table names for "dbo" schema
tablenames.Add(table);
}
}
foreach(string table in tablenames){
if(true){
SqlDataReader reader = new SqlCommand("SELECT * FROM " table, conn).ExecuteReader();
//Iterating the entire list of table names and getting the column names
for(int column = 0; column < reader.FieldCount; column ){
Console.WriteLine("Catalog - dbo - " table " - " reader.GetName(column));
}
reader.Close();
}
}
Console.WriteLine("END");
Console.ReadLine();
However, the list that I get doesn't display (among others) the first table "AccountBillingCode", even though I know it's contained within the list of strings. If I change the statement:
if(true)
by
if(table.StartsWith('A'))
Then, "AccountBillingCode" is listed in the output.
I don't understand why there are some tables getting excluded from my code.
Any ideas?
Thanks!
CodePudding user response:
Something like this as an idea.
select
t.name,c.name
from
sys.tables as t
left join sys.columns as c on t.object_id=c.object_id
order by t.name,c.column_id
CodePudding user response:
Apparently, there's nothing wrong with the code. It's just the code is too long for the Console, and when copying from there, the content at the top is missing. Disappointing mystery this time. Sorry! Thanks for the answers anyway!