Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

not really an ISSUE - here is a version for Azure SQL #3

Open
Davidcc opened this issue Nov 25, 2019 · 1 comment
Open

not really an ISSUE - here is a version for Azure SQL #3

Davidcc opened this issue Nov 25, 2019 · 1 comment

Comments

@Davidcc
Copy link

Davidcc commented Nov 25, 2019

WITH tableKeys AS (
SELECT t.constraint_schema,
t.table_name,
c.column_name,
'PK' AS column_key
FROM information_schema.table_constraints t
JOIN information_schema.constraint_column_usage c
ON c.constraint_schema = t.constraint_schema
AND c.table_name = t.table_name
AND c.constraint_name = t.constraint_name
WHERE t.constraint_type = 'PRIMARY KEY'
),
tableColumns AS (
SELECT t.table_schema,
t.table_name,
c.column_name,
COALESCE(tk.column_key,'') AS column_pk,
data_type AS column_type
FROM information_schema.columns c
JOIN information_schema.tables t
ON c.table_schema = t.table_schema
AND c.table_name = t.table_name
LEFT JOIN tableKeys tk
ON tk.constraint_schema = t.table_schema
AND tk.table_name = t.table_name
AND tk.column_name = c.column_name
WHERE t.table_type = 'BASE TABLE'
-- ORDER BY t.table_name, c.ordinal_position
),
tableDefs AS(
SELECT table_schema,
CONCAT_WS(' ','Table',table_name,'{',CHAR(10)) AS table_prefix,
CAST(STRING_AGG(CONCAT_WS(' ',' ',column_name,column_type,column_pk),CHAR(10)) AS NVARCHAR(MAX)) AS column_list,
CONCAT(CHAR(10),'}',CHAR(10)) AS table_suffix
FROM tableColumns
GROUP BY table_schema, table_name
-- ORDER BY 2
),
relDefs AS (
SELECT tc.table_schema,
CONCAT('Ref: ',tc.table_name,'.',kcu.column_name,' > ',object_name(sfk.referenced_object_id),'.',COL_NAME(sfk.referenced_object_id,1) ,CHAR(10)) AS relationships
FROM information_schema.table_constraints AS tc
JOIN information_schema.key_column_usage AS kcu
ON tc.constraint_name = kcu.constraint_name
AND tc.table_schema = kcu.table_schema
JOIN information_schema.constraint_column_usage AS ccu
ON ccu.constraint_name = tc.constraint_name
AND ccu.table_schema = tc.table_schema
JOIN sys.foreign_keys AS sfk
ON sfk.name = tc.CONSTRAINT_NAME
WHERE tc.constraint_type = 'FOREIGN KEY'
)
SELECT CONCAT(table_prefix,CAST(column_list AS NVARCHAR(MAX)),table_suffix) AS ddl
FROM tableDefs
-- WHERE table_schema = 'public'
UNION ALL
SELECT relationships AS ddl
FROM relDefs
--WHERE table_schema = 'dbo'

@matthewoldham
Copy link
Owner

Thanks @Davidcc! Would you mind creating a pull request with this code so I can properly acknowledge your contribution to this repository?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants