如何在 Sql 中创建用户定义类型

how to create user defined Type in Sql

我不知道如何创建具有可选约束的域? 我试过了

CREATE DOMAIN idx INT CHECK (VALUE > 100 AND VALUE < 999);

但遇到以下错误 CREATE、DROP 或 ALTER 语句中使用了未知对象类型 'DOMAIN'。

CREATE TYPE myType AS TABLE
(
   idx INT,
   CHECK (idx > 100 AND idx < 999)
)

或者您也可以创建规则并将它们绑定到您的类型。

CREATE TYPE [dbo].[myType] 
FROM [INT] NOT NULL
GO

CREATE RULE multiplyByTen
AS @myType % 10 = 0
AND @myType > 100
AND @myType < 999

然后Bind Rule

EXEC sp_bindrule 'multiplyByTen', 'myType'

您可能想看看 this

它解释了如何在 sql-server 中创建类型。有3种类型。您尝试创建的那个不允许添加 CHECK CONSTRAINT。您需要改用 rules

在您的情况下,您应该使用以下查询:

--First we create the rule.
CREATE RULE range_rule  
AS   
    @range >= 100 AND @range < 999; 
GO

--Then we create the user-defined data type
CREATE TYPE int_and_range FROM INT;

--Then we bind the rule to the data type.
EXEC sys.sp_bindrule @rulename=N'[dbo].[range_rule]', @objname=N'[dbo].[int_and_range]'

这样做之后,我们可以进行这样的测试:

CREATE TABLE test_table (
    custom_data_type_column int_and_range
)

--Try to insert a value against our rule
INSERT INTO dbo.test_table
        ( custom_data_type_column )
VALUES  ( 10  
          )

--RESULT:
--A column insert or update conflicts with a rule imposed by a previous CREATE RULE statement. The statement was terminated. 
--The conflict occurred in database 'db', table 'dbo.test_table', column 'custom_data_type_column'.  
--The statement has been terminated.

--Inserting a valid data:  
INSERT INTO dbo.test_table
        ( custom_data_type_column )
VALUES  ( 100 )

--RESULT:
--(1 row(s) affected)

--Select
Select * FROM test_table

--RESULT:

custom_data_type_column
-----------------------
100

(1 row(s) affected)

请注意,CREATE RULE 页面显示:

This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications that currently use this feature. We recommend that you use check constraints instead. Check constraints are created by using the CHECK keyword of CREATE TABLE or ALTER TABLE. For more information, see Unique Constraints and Check Constraints.