用什么语句决定插入语句是否通过

时间:2017-12-26 14:09:53

标签: sql-server

例如,我有2个表

Create table Authorized
(D_ID char(5), MNUM char(5), primary key(D_ID,MNUM), 
foreign key(D_ID) REFERENCES Distributor(D_ID),
foreign key(MNUM) REFERENCES Model(MNUM));

Create table Orders
(ORDNO char(8), D_ID char(5), MNUM char(5), 
Qty int, Date date,  primary key (ORDNO,D_ID,MNUM),
foreign key(MNUM) REFERENCES Model(MNUM),
foreign key(D_ID) REFERENCES Distributor(D_ID));

INSERT INTO Authorized VALUES ('D0003', 'M0001');
INSERT INTO Authorized VALUES ('D0003', 'M0003');

如何确保订单表的insert语句仅限于授权的D_ID?就像声明是

一样
INSERT INTO Orders VALUES 
('20161232', 'D0003','M0002',2, '2016-12-22');

如何防止此插入语句通过? AS M0002未获得授权

1 个答案:

答案 0 :(得分:1)

您可以创建Scalar函数并在表格中使用它:

CREATE FUNCTION IsAuthorized
(
    @Value CHAR(5) --I think you mean "MNUM" column here
)
RETURNS BIT
AS
BEGIN
    DECLARE @Result BIT = 0;
    IF EXISTS (SELECT 1 FROM Authorized WHERE D_ID = @Value)
        SET @Result = 1;
    RETURN(@Result);
END;
GO

以下是如何在表格中使用它:

Create table Orders(
    ORDNO char(8), 
    D_ID char(5) CONSTRAINT CHK_IsAuthorized CHECK(IsAuthorized(D_ID) = 1), 
    MNUM char(5),
    ...
    ...