Create MS SQL Server Database Table Relationship using Python

This blog article shows you how to extract the primary and foreign keys from MS SQL Database. The code snippet as follows.

import pyodbc
import pandas as pd

# Connect to the SQL Server database

conn = pyodbc.connect(‘DRIVER={SQL Server};SERVER=.;DATABASE=northwind;Trusted_Connection=yes;TrustServerCertificate=true’)

# Retrieve primary keys information

primary_keys_query = “””
SELECT
     TABLE_NAME,
     COLUMN_NAME
FROM
     INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
     CONSTRAINT_NAME LIKE ‘PK_%’
“””
primary_keys_df = pd.read_sql_query(primary_keys_query, conn)
# Retrieve foreign keys information
foreign_keys_query = “””
SELECT
     FK.TABLE_NAME AS ‘Table Name’,
     CU.COLUMN_NAME AS ‘Column Name’,
     PK.TABLE_NAME AS ‘Referenced Table’,
     PT.COLUMN_NAME AS ‘Referenced Column’
FROM
     INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS C
     INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
     INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
     INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
     INNER JOIN (
         SELECT
             i1.TABLE_NAME,
             i2.COLUMN_NAME
         FROM
             INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS i1
             INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS i2 ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
         WHERE
             i1.CONSTRAINT_TYPE = ‘PRIMARY KEY’
     ) AS PT ON PT.TABLE_NAME = PK.TABLE_NAME
“””
foreign_keys_df = pd.read_sql_query(foreign_keys_query, conn)
# Export the data to an Excel file
with pd.ExcelWriter(‘outsystems_qa_keys.xlsx’) as writer:
     primary_keys_df.to_excel(writer, sheet_name=’Primary Keys’, index=False)
     foreign_keys_df.to_excel(writer, sheet_name=’Foreign Keys’, index=False)

clip_image002

I am running it against Northwind. You can see the output like the following.

Also: Generate Data Dictionary for MS SQL Database using Python

clip_image004

Source code download: https://github.com/chanmmn/python/tree/main/2024/pyrelations?WT.mc_id=DP-MVP-36769

Reference: https://pypi.org/project/pyodbc/?WT.mc_id=DP-MVP-36769

Unknown's avatar

About chanmingman

Since March 2011 Microsoft Live Spaces migrated to Wordpress (http://www.pcworld.com/article/206455/Microsoft_Live_Spaces_Moves_to_WordPress_An_FAQ.html) till now, I have is over 1 million viewers. This blog is about more than 50% telling you how to resolve error messages, especial for Microsoft products. The blog also has a lot of guidance teaching you how to get stated certain Microsoft technologies. The blog also uses as a help to keep my memory. The blog is never meant to give people consulting services or silver bullet solutions. It is a contribution to the community. Thanks for your support over the years. Ming Man is Microsoft MVP since year 2006. He is a software development manager for a multinational company. With 25 years of experience in the IT field, he has developed system using Clipper, COBOL, VB5, VB6, VB.NET, Java and C #. He has been using Visual Studio (.NET) since the Beta back in year 2000. He and the team have developed many projects using .NET platform such as SCM, and HR based applications. He is familiar with the N-Tier design of business application and is also an expert with database experience in MS SQL, Oracle and AS 400.
This entry was posted in .Net, Cloud, Community, Computers and Internet, Data Platform, programming and tagged . Bookmark the permalink.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.