Skip to content

Instantly share code, notes, and snippets.

@timgaunt
Last active July 26, 2021 09:39
Show Gist options
  • Save timgaunt/a88bb640d7c0a8db2b09dc65a60dbbdd to your computer and use it in GitHub Desktop.
Save timgaunt/a88bb640d7c0a8db2b09dc65a60dbbdd to your computer and use it in GitHub Desktop.
List the columns from a table
SELECT
c.name [Column Name],
CONCAT(
t.name,
CASE
WHEN t.name IN ('char', 'varchar','nchar','nvarchar') THEN
CONCAT('(', IIF(c.max_length=-1, 'MAX', CONVERT(VARCHAR(4),IIF(t.name IN ('nchar','nvarchar'), c.max_length/2, c.max_length))), ')')
WHEN t.name IN ('decimal','numeric') THEN
CONCAT('(', CONVERT(VARCHAR(4),c.precision), ',', CONVERT(VARCHAR(4),c.Scale)+')')
ELSE ''
END
) AS [Data Type],
-- t.name,
-- c.max_length 'Max Length in Bytes',
-- c.precision ,
-- c.scale ,
IIF(c.is_nullable=0, 'No', 'Yes') AS [Nullable],
IIF(i.is_primary_key IS NULL, 'No', 'Yes') AS [Primary Key]
FROM
sys.columns c
INNER JOIN sys.types t ON c.user_type_id = t.user_type_id
LEFT OUTER JOIN sys.index_columns ic
LEFT OUTER JOIN sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id ON ic.object_id = c.object_id AND ic.column_id = c.column_id AND i.is_primary_key=1
WHERE
c.object_id = OBJECT_ID('TableNameHere')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment