Solved: query to get column names and data types in sql server

SQL or Structured Query Language, is the standard language for dealing with Relational Databases. It can be used to perform tasks such as update data on a database, or get data from a database. Some common relational database management systems that use SQL are: Oracle, Sybase, Microsoft SQL Server, Access, etc. Although most database systems use SQL, most of them also have their own proprietary extensions that are usually only used on their system. However, the standard SQL commands such as “Select”, “Insert”, “Update”, “Delete”, “Create”, “Drop” can be used to accomplish almost everything that one needs to do with a database. Today’s topic will focus on how to get column names and data types in SQL server.

Getting Column Names and Data Types in SQL Server

SELECT c.name AS column_name,
       t.Name AS data_type,
       c.max_length,
       c.precision
FROM   sys.columns c
INNER JOIN sys.types t ON c.user_type_id = t.user_type_id
WHERE  c.object_id = OBJECT_ID('YourTableName')

This sample piece of code will return a list of columns, along with their associated data types, for a particular given table ‘YourTableName’. To dive further into this, let’s first understand what each part of the query is accomplishing.

Understanding the Code

The SELECT statement: This basically selects/Gathers the required information. In our case, we are gathering the name of the column, data type, max length, and precision.

The FROM statement: This specifies from where to gather the information. We are directing it to the ‘sys.columns’ table where the information about columns is saved.

The INNER JOIN statement: This is used to combine rows from two or more tables, based on a related column between them. Here, the related column is user_type_id.

The WHERE clause: This is used to filter records, it is used to extract only those records that fulfill a specified condition. Here we are directing it to find ‘YourTableName’.

Similar Functions and Libraries

There are other ways to get the same information. For instance, using the INFORMATION_SCHEMA.COLUMNS. This is a table in SQL Server that stores metadata about all columns in the database.

SELECT COLUMN_NAME, DATA_TYPE 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME = 'YourTableName'

Another way is to use sp_help stored procedure. It returns information about the database object, a user-defined data type or a data type.

EXEC sp_help 'YourTableName';

Both of these methods yield the same information as the first method, but are structured a bit differently to suit various needs and preferences. In sum, these methods help developers to retrieve essential information about database columns and their data types in SQL Server.

Related posts:

Leave a Comment