约束基于两个表的关系?

时间:2014-03-24 16:33:08

标签: sql-server tsql sql-server-2012 constraints

基本上我只想在表B中的列为NULL时允许表A中的编辑/更新。表A和表B引用相同的主键id。所以像;

-- Only allow Table A to be updated when Table B column is NULL

update TableA
set blah = @a, foo = @b
from tablea
inner join tableb on tablea.id = tableb.id
where tableb.column is null

有没有办法将其用作表A的约束?

1 个答案:

答案 0 :(得分:1)

CREATE TRIGGER tr_Instead_Update_Table_A
ON TABLEA
INSTEAD OF UPDATE
AS
BEGIN
  SET NOCOUNT ON;

   IF NOT EXISTS(SELECT 1 
                FROM deleted d INNER JOIN TableB B
                ON d.PK_Column = B.PK_Column
                WHERE B.ColumnName IS NULL)
    BEGIN
        RAISERROR('Invalid update',16,1)
        RETURN;
    END

  -- Your update statement here 

END