Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get constraints on a SQL table column

Tags:

sql

sql-server

I have a column called MealType (VARCHAR) in my table with a CHECK constraint for {"Veg", "NonVeg", "Vegan"}

That'll take care of insertion.

I'd like to display these options for selection, but I couldn't figure out the SQL query to find out the constraints of a particular column in a table.

From a first glance at system tables in MS SQL server, it seems like I'll need to use MS SQL's API to get the info. I was hoping for a SQL query itself to get it.

like image 633
Raja Avatar asked Sep 04 '13 19:09

Raja


People also ask

How do you check constraints on a column?

The CHECK constraint is used to limit the value range that can be placed in a column. If you define a CHECK constraint on a column it will allow only certain values for this column. If you define a CHECK constraint on a table it can limit the values in certain columns based on values in other columns in the row.

How do I list constraints on a table in SQL?

Here, we display the name(CONSTRAINT_NAME) and the type of the constraint(CONSTRAINT_TYPE) for all existing constraints. Syntax: SELECT INFORMATION FROM INFORMATION_SCHEMA. TABLE_CONSTRAINTS WHERE TABLE_NAME='TABLE_NAME';

How do you find constraints on a table?

In Oracle, use the view user_constraints to display the names of the constraints in the database. The column constraint_name contains the name of the constraint, constraint_type indicates the type of constraint, and table_name contains the name of the table to which the constraint belongs.

How do I find constraints on a table in SQL Server?

In the Object Explorer, right-click the table containing the check constraint and select Design. On the Table Designer menu, click Check Constraints.... In the Check Constraints dialog box, under Selected Check Constraint, select the constraint you wish to edit.


2 Answers

Easiest and quickest way is to use:

sp_help 'TableName'
like image 110
Zonus Avatar answered Oct 05 '22 23:10

Zonus


This query should show you all the constraints on a table:

select chk.definition
from sys.check_constraints chk
inner join sys.columns col
    on chk.parent_object_id = col.object_id
inner join sys.tables st
    on chk.parent_object_id = st.object_id
where 
st.name = 'Tablename'
and col.column_id = chk.parent_column_id

can replace the select statement with this:

select substring(chk.Definition,2,3),substring(chk.Definition,9,6),substring(chk.Definition,20,5) 
like image 32
orgtigger Avatar answered Oct 06 '22 01:10

orgtigger