您可以對此使用檢查約束。 (該代碼是未測試的一些語法錯誤將在那裏)
CREATE TABLE Member
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
InternalContactId
CONSTRAINT chk_Person CHECK (isInternalUser(internalContactId) > 0)
)
ALTER TABLE Member
ADD FOREIGN KEY (InternalContacId)
REFERENCES Persons(P_Id)
然後,只需創建一個函數iniInternalUser返回1,如果用戶在確定是內部接觸
CREATE FUNCTION isInternalUser (@userId int(10))
RETURNS int
AS
BEGIN
DECLARE @tmp int
SELECT @tmp = count(*)
FROM users
WHERE userId = @UserId and <check to see if user is ineternal
RETURN(@CtrPrice)
END
GO
這一問題的可能的重複:http://stackoverflow.com/questions/2409033/sql-server-conditional-foreign-key-constraints – 2015-03-13 08:32:38
我認爲你可以創建檢查約束。此外,這是理想scenrio而不是觸發器.IMHO,而不是觸發器將更多優化。我錯了嗎? – KumarHarsh 2015-03-13 08:36:00