Advertisement
Mite123

Untitled

Jan 30th, 2025
39
0
6 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MySQL 1.34 KB | Source Code | 0 0
  1. SELECT
  2.     DISTINCT c.object_id,
  3.     s.name AS SchemaName,
  4.     t.name AS TableName,
  5.     c.name AS ColumnName,
  6.     c.column_id AS ColumnID,
  7.     ty.name AS DataType,
  8.     c.max_length AS MaxLength,
  9.     c.is_nullable AS IsNullable,
  10.     fk.name as RelationshipName,
  11.     CASE
  12.         WHEN ic.column_id = c.column_id AND ic.object_id = c.object_id THEN 1
  13.         ELSE 0
  14.     END AS IsPrimaryKey,
  15.     CASE
  16.         WHEN fk.parent_object_id = c.object_id THEN 1
  17.         ELSE 0
  18.     END AS IsForeignKey
  19.  
  20. FROM sys.columns c  -- Columns table
  21. JOIN sys.tables t   -- Tables table join on columns.objectId and tables.objectid seems like they have the same ids
  22.     ON c.object_id = t.object_id
  23. JOIN sys.schemas s  -- inner join with the schemas on table schema_Id and the schemaId
  24.     ON t.schema_id = s.schema_id
  25. JOIN sys.types ty
  26.     ON c.user_type_id = ty.user_type_id -- Inner join on tye types ID to get the columns types
  27. LEFT JOIN sys.foreign_keys as fk
  28.     ON t.object_id = fk.parent_object_id -- inner join to the foreign_keys to get if a column is a foreign key
  29. LEFT JOIN sys.key_constraints pks
  30.     ON pks.parent_object_id = c.object_id AND t.object_id = pks.parent_object_id --1
  31. JOIN sys.index_columns ic ON pks.unique_index_id = ic.index_id AND pks.parent_object_id = ic.object_id -- 3 to get enough data to determine the PK
  32.  
  33. WHERE s.name = 'dbo'
  34.  
  35. ORDER BY s.name, t.name, c.column_id;
Tags: sql
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement