Created
February 20, 2019 04:40
-
-
Save ConradStack/3c931a0e2e086c4754ac2823ee60b89d to your computer and use it in GitHub Desktop.
SQL server query to get the list of columns in a table along with Data types, NOT NULL, and PRIMARY KEY constraints
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
From [this stackover post](https://stackoverflow.com/questions/2418527/sql-server-query-to-get-the-list-of-columns-in-a-table-along-with-data-types-no) | |
*/ | |
SELECT | |
c.name 'Column Name', | |
t.Name 'Data type', | |
c.max_length 'Max Length', | |
c.precision , | |
c.scale , | |
c.is_nullable, | |
ISNULL(i.is_primary_key, 0) 'Primary Key' | |
FROM | |
sys.columns c | |
INNER JOIN | |
sys.types t ON c.user_type_id = t.user_type_id | |
LEFT OUTER JOIN | |
sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id | |
LEFT OUTER JOIN | |
sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id | |
WHERE | |
c.object_id = OBJECT_ID('YourTableName') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For default value too, try these:
SELECT object_definition(default_object_id) AS definition FROM sys.columns WHERE name ='colname' AND object_id = object_id('dbo.tablename')
or linking to the column explicitly:
LEFT OUTER JOIN sys.default_constraints dc ON dc.parent_column_id = c.column_id
https://docs.microsoft.com/en-us/sql/t-sql/functions/object-definition-transact-sql?view=sql-server-2017