您需要创建一个索引视图,该视图可以有效地合并预告片。
为此,您必须创建一个小型支持表:
CREATE TABLE place (id INT NOT NULL PRIMARY KEY)
INSERT
INTO place
VALUES (1),
(2)
GO
CREATE VIEW
v_truck_trailers
WITH SCHEMABINDING
AS
SELECT t.id AS truckId,
p.id AS placeId,
CASE p.id WHEN 1 THEN trailer1 WHEN 2 THEN trailer2 END AS trailerId
FROM dbo.truck t
JOIN dbo.place p
ON CASE p.id WHEN 1 THEN trailer1 WHEN 2 THEN trailer2 END IS NOT NULL
GO
CREATE UNIQUE CLUSTERED INDEX
ux_v_truck_trailers_truck_place
ON v_truck_trailers (truckId, placeId)
GO
CREATE UNIQUE INDEX
ux_v_truck_trailers_trailer
ON v_truck_trailers (trailerId)
GO
现在让我们尝试一下:
INSERT
INTO truck
VALUES (1, 1, NULL) -- succeeds
INSERT
INTO truck
VALUES (2, 2, 3) -- also succeeds
INSERT
INTO truck
VALUES (3, NULL, 2) -- fails as trailer 2 is already used on truck 2, even if on another place.
请参阅SQLFiddle。