📜  sql server 设置复杂约束 - SQL 代码示例

📅  最后修改于: 2022-03-11 15:05:09.004000             🧑  作者: Mango

代码示例1
CREATE FUNCTION dbo.fnIsAddressOwner (
  @CustomerId int,
  @AddressId int
)
RETURNS tinyint
AS
BEGIN
  DECLARE @Result tinyint
  IF EXISTS(SELECT * FROM CustomerAddresses WHERE CustomerId=@CustomerId and AddressId=@AddressId)
    SET @Result= 1
  ELSE 
    SET @Result= 0
  RETURN @Result
END


CREATE TABLE Customers (
  CustomerId int,
  PreferredAddressId int,
  CONSTRAINT ckPreferredAddressId CHECK (
    dbo.fnIsAddressOwner(CustomerId, PreferredAddressId) = 1)
  )
)