Home > OS >  How to loop through all tables in a SQL Server database
How to loop through all tables in a SQL Server database

Time:01-02

I would want to loop through all the tables in a database using C# and list them in a listBox1 (preferably a foreach loop):

SSMS screenshot

I CANNOT just create a local list of tables names, because they are constantly being added/removed.

Could someone provide an example?

BTW: no I'm not creating a software for pirated movies

CodePudding user response:

As you're using C#, have a look at SMO. Here's a demonstration via powershell (which is an expedient way for me to demonstrate):

$db_server = New-Object Microsoft.SqlServer.Management.SMO.Server .;
$db = $db_server.Databases['AdventureWorks2019'];
$tables = $db.Tables;

CodePudding user response:

See if this works after logging into SQL Server database:

select schema_name(t.schema_id) as schema_name,
       t.name as table_name,
       t.create_date,
       t.modify_date
from sys.tables t
order by schema_name,
         table_name;

If you can get it working to produce the fields you want, then you just need to write the code to do it in C#.

  • Related