问题
I want to create a type in sql-server which is similar to DOMAIN in postgresql.
CREATE DOMAIN degree_level NVARCHAR(10)
CONSTRAINT degree_level_test
CHECK (VALUES IN (’Bachelors’, ’Masters’, ’Doctorate’))
Note: I know this query is not correct.
Is it possible to create such types in SQL-server?
回答1:
In sql Server you will need to do this in two steps
1) Create a Type
2) Create a constraint
Create A TYPE
CREATE TYPE dbo.degree_level FROM NVARCHAR(10)
GO
Create a Constraint on Table Level
CREATE TABLE Type_Test_Table
(
ID INT ,
Type_Column degree_level
CHECK (Type_Column IN( 'Bachelors' , 'Masters' ,'Doctorate'))
)
GO
Test
INSERT INTO Type_Test_Table VALUES (1, 'Bachelors') --<-- Success
GO
INSERT INTO Type_Test_Table VALUES (2, 'Masters') --<-- Success
GO
INSERT INTO Type_Test_Table VALUES (3, 'Doctorate') --<-- Success
GO
INSERT INTO Type_Test_Table VALUES (4, 'Other Val') --<-- Fail
GO
来源:https://stackoverflow.com/questions/21803724/create-type-in-sql-server-with-allowed-values