T-SQL检查约束基于"层次结构"

时间:2016-11-16 15:07:03

标签: sql sql-server sql-server-2016

CREATE TABLE [dbo].[Test]
    ( [GID] INT
    , [ID] INT
    , [Val] VARCHAR(10)
    , [ParentId] INT
    , CONSTRAINT [PK_Test] PRIMARY KEY ( [GID], [ID] )
    , CONSTRAINT [FK_Test_ParentId] FOREIGN KEY ( [GID], [ParentId] ) REFERENCES [dbo].[Test] ( [GID], [id] ) );

INSERT INTO [dbo].[Test] ([GID], [ID], [Val], [ParentId])
SELECT 1, 1,'One',NULL
UNION
SELECT 1, 2,'Two',NULL
UNION
SELECT 1, 3,'Three',1
UNION
SELECT 1, 4,'Four',1
UNION
SELECT 2, 1,'One',NULL
UNION
SELECT 2, 2,'Two',1;

SELECT  *
FROM    [dbo].[Test];

/* Test Cases */
--UPDATE    [dbo].[Test]
--SET       [ParentId] = 2
--WHERE     [GID] = 1 AND [ID] = 1; -- Should FAIL because this record is already marked as a Parent of another record(s) (i.e. [GID] = 1 AND [ID] IN (3, 4)

--INSERT    INTO [dbo].[Test] ( [GID], [ID], [Val], [ParentId] )
--SELECT    1, 5, 'Five', 4; -- Should FAIL because [GID] = 1 AND [ID] = 4 already has a non-null [ParentId].

DROP TABLE [dbo].[Test];

目标:
创建一个检查约束(带有BIT返回的标量函数,其中1 =有效,0 =无效?),以防止映射的ParentID记录具有NOT-NULL ParentId或阻止具有已经具有NOT-的ParentId的记录的INSERT NULL分配给它的ParentID。

我尝试使用LEFT Joins / NULL检查逻辑,但没有真正得到我正在寻找的东西。

0 个答案:

没有答案