anil Kumar
anil Kumar

Reputation: 41

How to get column names from database?

I'm working with Entity Framework. Is there any method to get the column names of a table from the database?

I want to display all the column names which are in the database.

Upvotes: 1

Views: 615

Answers (2)

Devart
Devart

Reputation: 122040

This query is similar to marc_s's one, but uses sys.objects instead of sys.tables. The system table sys.tables contains many hidden JOIN statements, so this query should be faster -

SELECT
  column_name = c.name,
  table_name = s.name + '.' + o.name
FROM sys.columns c 
JOIN sys.objects o ON c.object_id = o.object_id
JOIN sys.schemas s ON o.schema_id = s.schema_id
WHERE o.type = 'U'

Upvotes: 1

marc_s
marc_s

Reputation: 755541

Not directly from Entity Framework, as far as I know - but you can always execute a standard T-SQL query against the catalog views:

SELECT
    ColumnName = c.Name,
    SchemaName = s.Name, 
    TableName = t.Name
FROM
    sys.columns c 
INNER JOIN 
    sys.tables t ON c.object_id = t.object_id
INNER JOIN 
    sys.schemas s ON t.schema_id = s.schema_id

This would give you all columns, along with the schema and table they're part of, from your current SQL Server database.

Upvotes: 1

Related Questions