I want to query the name of all columns of a table. I found how to do this in:
But I also need to know:
SELECT c.Name
FROM sys.columns c
JOIN sys.objects o ON o.object_id = c.object_id
WHERE o.object_id = OBJECT_ID('TABLE_NAME')
ORDER BY c.Name
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'name_of_your_table'
SELECT name
FROM sys.columns
WHERE object_id = OBJECT_ID('TABLE_NAME')
TABLE_NAME
is your table
By using this query you get the answer:
select Column_name
from Information_schema.columns
where Table_name like 'table name'
Summarizing the Answers
I can see many different answers and ways to do this but there is the rub in this and that is the objective
.
Yes, the objective. If you want to only know
the column names you can use
SELECT * FROM my_table WHERE 1=0
or
SELECT TOP 0 * FROM my_table
But if you want to use
those columns somewhere or simply say manipulate
them then the quick queries above are not going to be of any use. You need to use
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'Customers'
one more way to know some specific columns where we are in need of some similar columns
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME like N'%[ColumnName]%' and TABLE_NAME = N'[TableName]'
select *
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='tableName'
This is better than getting from sys.columns
because it shows DATA_TYPE
directly.