COL_NAME is a predefined SQL server function that returns the name of a table column using table and column identification numbers.
COL_NAME (table_id, column_id)
COL_NAME function takes two parameters which is table and column identification numbers like specified in the above statement.
Let's look into an example of AdventureWorks2019 database,
SELECT TOP (1000) [BusinessEntityID]
,[PersonType]
,[NameStyle]
,[Title]
,[FirstName]
,[MiddleName]
,[LastName]
,[Suffix]
,[EmailPromotion]
,[AdditionalContactInfo]
,[Demographics]
,[rowguid]
,[ModifiedDate]
FROM [AdventureWorks2019].[Person].[Person]
Here is the above statement result set,
Let's see how to retrieve the column name FirstName using the COL_NAME function,
SELECT COL_NAME(OBJECT_ID('Person.Person'), 5) AS ColumnName; /* COL_NAME (table_id, column_id) */
The OBJECT_ID function returns the identification number of a specified table and number 5 represents the column number.
Comments