create type in sql server with allowed values

不羁岁月 提交于 2019-12-08 12:20:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!