SQL Server – How to Get Column Names From a Specific Table?

I get column names from schema-qualified table metadata. Catalog views help when I also need SQL Server-specific details.

A selected compartmented drawer is inspected with a brass measuring tool while other drawers stay closed.

Run this in the database containing the table and set both schema and table name. The original scripts left their filters commented out, so they listed more than the requested table.

DECLARE @Schema sysname = N'HumanResources', @Table sysname = N'Employee';
SELECT COLUMN_NAME, DATA_TYPE, ORDINAL_POSITION
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = @Schema AND TABLE_NAME = @Table
ORDER BY ORDINAL_POSITION;
SELECT s.name AS SchemaName, o.name AS TableName, c.name AS ColumnName,
       t.name AS DataType, c.max_length AS MaxLengthBytes,
       c.precision AS NumericPrecision, c.scale AS NumericScale
FROM sys.tables AS o
JOIN sys.schemas AS s ON s.schema_id = o.schema_id
JOIN sys.columns AS c ON c.object_id = o.object_id
JOIN sys.types AS t ON t.user_type_id = c.user_type_id
WHERE s.name = @Schema AND o.name = @Table
ORDER BY c.column_id;
Original catalog-query result. The local revision uses schema filtering and column order rather than alphabetical order.
Original catalog-query result. The local revision uses schema filtering and column order rather than alphabetical order.

Use c.max_length for the column, rather than the type’s default length. It reports bytes, with -1 for max types. Precision and scale describe separate numeric attributes. Permissions affect visibility, so no rows can mean invisible as well as absent.

Reference: sys.columns.

Original video

A column length is not always a character count, it is metadata whose units depend on the data type.

Published by Pinal Dave on SQLAuthority. More of my work at pinaldave.com.


Discover more from SQL Authority with Pinal Dave

Subscribe to get the latest posts sent to your email.

SQL Scripts, SQL Server, SQL System Table
Previous Post
MySQL – Fix – Error – Your Password does not Satisfy the Current Policy Requirements
Next Post
Log Shipping Alternative for Databases in Simple Recovery Model

Related Posts

17 Comments. Leave new

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.