Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where can I set a check constraint in SSMS Table Designer Mode

So here I have a table:

enter image description here

What I want is to add a check constraint for the column SessionState in the above designer mode so it can work like a enum. But unfortunately, I can't find the place where I can do that.

I tried right also "right click -> script table as-> create table" but here I can't make a not null check:

enter image description here

like image 526
Lebron11 Avatar asked Oct 17 '22 19:10

Lebron11


1 Answers

Right-click on the SessionState and Select Check Constraints...
Then add your constraint.

enter image description here

Or Select dbo.Table > Constraints > New Constraints... > Expression (under General) and then enter your expression.

([SessionState]='Unknown' OR [SessionState]='Useless' OR [SessionState]='Useful')

enter image description here
Img Full Size: https://i.stack.imgur.com/AvgJX.png

enter image description here
Img Full Size: https://i.stack.imgur.com/HMsEK.png

Or simply enter this code

Alter Table TableName
ADD CONSTRAINT Constraint_name Check (SessionState IN ('Useful', 'Useless', 'Unknown'))

Updated

(Backup all data)

Run this query and get all null & unsupported values. Then, change them (change SessionState values).

Select * from [Session] WHERE SessionState IS NULL OR SessionState NOT IN ('Useful', 'Useless', 'Unknown')

To change, use this queries...

UPDATE [Session] SET SessionState='Unknown' WHERE SessionState IS NULL

UPDATE [Session] SET SessionState='Unknown' WHERE SessionState NOT IN ('Useful', 'Useless', 'Unknown')

Do the first step again after changing the values.

Then run these queries...

Alter Table Session
ALTER COLUMN SessionState nchar(40) NOT NULL

Alter Table Session
ADD CONSTRAINT Constraint_name Check (SessionState IN ('Useful', 'Useless', 'Unknown'))

Demo: http://rextester.com/TGW65894

For additional information, refer this video: https://youtu.be/9Zj5ODhv0b0

like image 148
DxTx Avatar answered Oct 21 '22 01:10

DxTx