Last active
May 30, 2025 14:39
-
-
Save Roenbaeck/253622c5d292739cb2ccd6ecab5b01c1 to your computer and use it in GitHub Desktop.
This is a stored procedure for SQL Server that formats the output of an SQL query as Markdown.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
USE master; | |
GO | |
/* | |
2025-04-14 Lars Rönnbäck CREATED | |
2025-04-15 Lars Rönnbäck Renamed to dbo.sp_Markdown. | |
Uses FOR XML AUTO and REPLACE to handle spaces in column names. | |
2025-05-26 Lars Rönnbäck Handle NULL values. | |
Detection of last element through local-name(). | |
TEST: | |
sp_Markdown 'SELECT * FROM master.sys.schemas' | |
*/ | |
CREATE OR ALTER PROC dbo.sp_Markdown ( | |
@SQL VARCHAR(MAX), | |
@null VARCHAR(555) = 'NULL' | |
) | |
AS | |
BEGIN | |
-- FOR XML AUTO converts spaces to _x0020_ since they are not allowed in XML tags. | |
-- If other characters are converted the REPLACE below may need to be extended. | |
SET @SQL = ' | |
SELECT REPLACE(R.value(''.'', ''varchar(max)''), ''_x0020_'', '' '') AS [Markdown] | |
FROM ( | |
SELECT ( | |
SELECT * | |
FROM ( ' + @SQL + ') s | |
FOR XML AUTO, ELEMENTS XSINIL, TYPE | |
).query('' | |
for $r in *[1] | |
let $last := $r/*[last()] | |
return <R>{ | |
for $x in $r/* | |
return | |
if (local-name($x) = local-name($last)) then | |
concat("| ", local-name($x), " |") | |
else | |
concat("| ", local-name($x)) | |
}</R>, | |
for $r in *[1] | |
let $last := $r/*[last()] | |
return <R>{ | |
for $x in $r/* | |
return | |
if (local-name($x) = local-name($last)) then | |
"|-----|" | |
else | |
"|-----" | |
}</R>, | |
for $r in * | |
let $last := $r/*[last()] | |
return <R>{ | |
for $x in $r/* | |
return | |
if (local-name($x) = local-name($last) and $x/@xsi:nil = "true") then | |
"| ' + @null + ' |" | |
else if (local-name($x) = local-name($last)) then | |
concat("| ", string($x), " |") | |
else if ($x/@xsi:nil = "true") then | |
"| ' + @null + '" | |
else | |
concat("| ", string($x)) | |
}</R> | |
'') | |
) X(V) | |
CROSS APPLY V.nodes(''R'') V(R) | |
'; | |
EXEC(@SQL); | |
END |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment