Thursday, March 8, 2012

Check constraint

I am new to SQL Server, so I'm not quite sure how to use this feature. I need to limit a field to only accept a set of three values: H, Q, and C. I know how to do this in a native Access table. I'm not quite sure how to do this in SQL Server. I assum
e this is what a check constraint is, but I don't know how to set one up or where to implement it.
Any suggestions would be greatly appreciated,
Crystal
Yep, it's a check constraint:
create table MyTable
(
PK int primary key
, MyCol char (1) not null constraint CK_MyTable (MyCol in ('H', 'Q',
'C'))
)
Tom
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinnaclepublishing.com/sql
..
"Crystal" <anonymous@.discussions.microsoft.com> wrote in message
news:BC380E12-BD25-4308-8860-08617207DEE4@.microsoft.com...
I am new to SQL Server, so I'm not quite sure how to use this feature. I
need to limit a field to only accept a set of three values: H, Q, and C. I
know how to do this in a native Access table. I'm not quite sure how to do
this in SQL Server. I assume this is what a check constraint is, but I
don't know how to set one up or where to implement it.
Any suggestions would be greatly appreciated,
Crystal
|||Try this -
create table test (
iintidentity
, jchar(1)
check (j in ('H', 'Q', 'C'))
)
|||Ok. This is what is going to make me look like a dork. . .
Now that I have the syntax. . . where do I put it to create the check constraint?
Crystal
|||The syntax I showed you is to create the constraint at the time you create
the table. However, if the table already exists, you can do an ALTER TABLE:
alter table MyTable
add
constraint CK_MyTable (MyCol in ('H', 'Q', 'C'))
go
Tom
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinnaclepublishing.com/sql
"Crystal" <anonymous@.discussions.microsoft.com> wrote in message
news:CFC4AF0F-052F-442A-8037-307EC3A3D437@.microsoft.com...
Ok. This is what is going to make me look like a dork. . .
Now that I have the syntax. . . where do I put it to create the check
constraint?
Crystal

No comments:

Post a Comment