Printing all tables in a database with Management.Smo
February 18, 2010
The Microsoft.SqlServer.Management.Smo namespace and assembly is used by Management Studio for its interogation of the database. If you have Management Studio installed you can use this in your own applications, a simple example of which is shown below.
This file contains 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
// From microsoft.sqlserver.smo.dll | |
using Microsoft.SqlServer.Management.Smo; | |
void PrintTables() | |
{ | |
Server server = new Server("(local)"); | |
server.ConnectionContext.ConnectAsUserName = "sa"; | |
server.ConnectionContext.ConnectAsUserPassword = "Passw0rd"; | |
Database db = server.Databases["mydatabase"]; | |
foreach (Table table in db.Tables) | |
{ | |
Console.WriteLine(string.Format("[{0}]", table.Name)); | |
foreach (Column column in table.Columns) | |
{ | |
Console.WriteLine(string.Format("\t{0} {1} {2} {3}", | |
column.Name, | |
column.DataType.Name, | |
column.Default, | |
column.DataType.MaximumLength)); | |
} | |
Console.WriteLine(""); | |
} | |
Console.Read(); | |
} | |
} |
I'm Chris Small, a software engineer working in London. This is my tech blog. Find out more about me via Github, Stackoverflow, Resume