简体   繁体   中英

SQL server query to get the list of columns in a table along with Data types, NOT NULL, and PRIMARY KEY,Foreignkey constraints in sql server

How to write this query to display all columns with the given properties and constraints, My expected output is:

Column name | Data type | Length | isnull | Pk | FK

All that you want is already done in sp_help .

You execute it passing it table name like this:

exec sp_help 'MyTable'

If you want to have another resultset you can extract all the queries from sp_help :

exec sp_helptext 'sp_help'

And ajust these queries to your needs.

This should do what you wanted

use [*MyDBName*]    
  Select Column_name, 
         data_type, 
         Character_maximum_length, 
         (Select Tab.Constraint_name 
          from INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab 
          left join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ColU on Tab.Constraint_name = colU.Constraint_name       
          where Tab.Table_name = Col.Table_name AND ColU.COLUMN_NAME = Col.Column_name  and Tab.CONSTRAINT_NAME like 'Pk[_]%'
         )  PK,
         (Select Tab.Constraint_name 
          from INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab 
          left join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ColU on Tab.Constraint_name = colU.Constraint_name       
          where Tab.Table_name = Col.Table_name AND ColU.COLUMN_NAME = Col.Column_name  and Tab.CONSTRAINT_NAME like 'Fk[_]%'
         )  FK
  FROM INFORMATION_SCHEMA.Columns Col
  WHERE Col.TABLE_NAME = '*MyTableName*'

For a particular table's columns

select COLUMN_NAME, DATA_TYPE, character_maximum_length, is_nullable from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'table_name'

For all tables columns

select COLUMN_NAME, DATA_TYPE, character_maximum_length, is_nullable from INFORMATION_SCHEMA.COLUMNS

For contraints

select * from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where table_name ='Table_name'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM