Skip to content

Instantly share code, notes, and snippets.

@alatas
Forked from asears/tablemeta.sql
Last active April 27, 2022 21:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alatas/087cbeefe7baafc25af9da65898a4b3a to your computer and use it in GitHub Desktop.
Save alatas/087cbeefe7baafc25af9da65898a4b3a to your computer and use it in GitHub Desktop.
Create markdown based on table metadata in SQL Server / SQL DW / Azure SQL
WITH c1
AS (SELECT
o.name AS tablename,
c.colid,
CONVERT(varchar(10), c.colid) + '|' + c.name + '|' + t.name + '|' + CONVERT(varchar(10), c.length) + '|' AS markdown
FROM sysobjects o
INNER JOIN syscolumns c
ON c.id = o.id
INNER JOIN systypes t
ON t.xtype = c.xtype
WHERE o.xtype = 'U'),
c2
AS (SELECT
*,
ROW_NUMBER() OVER (ORDER BY tablename, colid) rn,
ROW_NUMBER() OVER (PARTITION BY tablename, markdown ORDER BY tablename, colid) rn2
FROM c1
GROUP BY GROUPING SETS
(
tablename,
tablename,
tablename,
tablename,
(tablename, colid, markdown)
))
SELECT
CASE
WHEN markdown IS NULL AND
rn2 = 1 THEN ''
WHEN markdown IS NULL AND
rn2 = 2 THEN tablename
WHEN markdown IS NULL AND
rn2 = 3 THEN '|id|name|type|length|'
WHEN markdown IS NULL AND
rn2 = 4 THEN '|---|---|---|---|'
ELSE markdown
END
FROM c2
ORDER BY rn
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment