Tuesday, December 15, 2009

How to retrieve all the constraints on a particular column in a specific table?

The best way is to use INFORMATION_SCHEMA, INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME column in particular. Here is an example using Northwind database, Products table and ProductName column. SQL below will retrieve all the constraints on ProductName column:


DECLARE @tablename nvarchar(50)
DECLARE @column_name nvarchar(50)

SET @tablename = 'Products'
SET @column_name = 'ProductName'

SELECT INFORMATION_SCHEMA.TABLE_CONSTRAINTS.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
INNER JOIN INFORMATION_SCHEMA.COLUMNS ON INFORMATION_SCHEMA.TABLE_CONSTRAINTS.TABLE_NAME = INFORMATION_SCHEMA.COLUMNS.TABLE_NAME
WHERE INFORMATION_SCHEMA.TABLE_CONSTRAINTS.TABLE_NAME =@tablename
AND INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME=@columnname

No comments:

Post a Comment