sql-serverpython-2.7database-schema

Python - extracting a SQL Server database schema to a file


Often I need to extract the complete schema of an existing SQL Server DB to a file. I need to cover every object -- tables, views, functions, SPs, UDDTs, triggers, etc. The purpose is so that I can then use a file-diff utility to compare that schema to a baseline reference.

Normally I use Enterprise Manager or Management Studio to script out the DB objects and then concatenate those files to make one big file in a consistent predictable order. I was wondering whether there's a way to accomplish this task in Python? Obviously it'd take an additional package, but having looked at a few (pyodbc, SQLAlchemy, SQLObject), none of them seem really suited to this use case.


Solution

  • If you can connect to SQL Server and run queries in Python then yes – it’s possible but it will take a lot of effort and testing to get it to work correctly.

    Idea is to use system tables to get details about each object and then generate DDL statements based on this. Some if not all DDL statements already exist in sys.syscomments table.

    Start off by executing and examining this in SSMS before you start working in Python.

    select *
    from sys.tables
    
    select *
    from sys.all_columns
    
    select *
    from sys.views
    
    select *
    from sys.syscomments
    

    All system tables documentation from MSDN.