how to create user defined Type in Sql

r bhd picture r bhd · Feb 23, 2018 · Viewed 13.6k times · Source

i don't know how to create a domain with optional constrains? i tried

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

but faced the below err Unknown object type 'DOMAIN' used in a CREATE, DROP, or ALTER statement.

Answer

MadBert picture MadBert · Feb 23, 2018
CREATE TYPE myType AS TABLE
(
   idx INT,
   CHECK (idx > 100 AND idx < 999)
)

Or you can also create rules and bind them to your type.

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

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

Then Bind Rule

EXEC sp_bindrule 'multiplyByTen', 'myType'