I have a SQL Server database and I want to know what columns and types it has. I\'d prefer to do this through a query rather than using a GUI like Enterprise Manager. Is the
If you are using FirstResponderKit from Brent Ozar team, you can run this query also:
exec sp_blitzindex @tablename='MyTable'
It will return all information about table:
Of course it's not a system and not so universal stp like sp_help or sp_columns, but it returns all possible information about your table and I think it's worth creating it at your environment and mentioning it here.
There are a few methods to get metadata about a table:
EXEC sp_help tablename
Will return several result sets, describing the table, it's columns and constraints.
The INFORMATION_SCHEMA
views will give you the information you want, though unfortunately you have to query the views and join them manually.
In addition to above questions, if we have table in DB like db_name.dbo.table_name
, we may use following steps
Connect with DB
USE db_name;
Use EXEC sp_help
and don't forget to put table name as 'dbo.tablename'
if you have dbo
as schema.
exec sp_help 'dbo.table_name'
This should work!
The problem with those answers is that you're missing the key info. While this is a bit messy this is a quick version I came up with to make sure it contains the same info the MySQL Describe displays.
Select SC.name AS 'Field', ISC.DATA_TYPE AS 'Type', ISC.CHARACTER_MAXIMUM_LENGTH AS 'Length', SC.IS_NULLABLE AS 'Null', I.is_primary_key AS 'Key', SC.is_identity AS 'Identity'
From sys.columns AS SC
LEFT JOIN sys.index_columns AS IC
ON IC.object_id = OBJECT_ID('dbo.Expenses') AND
IC.column_id = SC.column_id
LEFT JOIN sys.indexes AS I
ON I.object_id = OBJECT_ID('dbo.Expenses') AND
IC.index_id = I.index_id
LEFT JOIN information_schema.columns ISC
ON ISC.TABLE_NAME = 'Expenses'
AND ISC.COLUMN_NAME = SC.name
WHERE SC.object_id = OBJECT_ID('dbo.Expenses')
In addition to the ways shown in other answers, you can use
SELECT TOP 0 * FROM table_name
This will give you the name of each column with no results in them, and completes almost instantly with minimal overhead.
You can use the sp_help 'TableName'