How to get all constraint on table?
Asked Answered
T

1

8

I want to store tables metadata into other table.So how to get all constraint and its type like whether it primary , unique or foreign key in MS SQL server.

table_name    |   constraint_name   |  constraint_type
--------------|---------------------|-------------------
user          |   pk_user_id        |   PRIMARY_KEY
user_role     |   fk_role           |   FOREIGN_KEY
user          |   unique_email      |   UNIQUE_KEY
Transmissible answered 2/1, 2015 at 11:38 Comment(1)
Why would you store this information yourself, its already stored and it bring a lot of maintenance with it?Mawkish
F
25

USE INFORMATION_SCHEMA.TABLE_CONSTRAINTS

SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_NAME='tablename'
Fiora answered 2/1, 2015 at 11:42 Comment(2)
This should be marked as the correct answerSkeens
Careful! This does not show DEFAULT constraints. sp_helpconstraint @objname = 'schema.tableName', @nomsg = NULL; might be more appropriate.Nastassia

© 2022 - 2024 — McMap. All rights reserved.