我有两个相互关联的表 (feature
和features
),我想让开发人员对id
一个表 ( feature
) 拥有的 (主键) 透明。因此,为了插入一个表(features
),您不必放入另一个表id
(feature
),您可以使用另一个表具有的辅助键。这是我的代码:
CREATE TABLE feature(
id INTEGER NOT NULL,
description VARCHAR(15) NOT NULL,
value VARCHAR(15) NOT NULL,
price MONEY NOT NULL,
CONSTRAINT feature_pk PRIMARY KEY(id),
CONSTRAINT feature_un UNIQUE(description, value),
CONSTRAINT feature_ck_price CHECK(price >= 0)
);
CREATE TABLE features(
name VARCHAR(20) NOT NULL,
year NUMERIC(4) NOT NULL,
feature_id INTEGER NOT NULL,
CONSTRAINT features_pk PRIMARY KEY(name,year,feature_id),
CONSTRAINT features_fk_model FOREIGN KEY(name,year) REFERENCES model(name,year),
CONSTRAINT features_pk_feature FOREIGN KEY(feature_id) REFERENCES feature(id)
);
-- Trigger not working because the features table doesnt have the columns I'm trying to use.
CREATE TRIGGER trigger_features_get_feature_id
ON features
INSTEAD OF INSERT
AS
DECLARE
@tr_features_name VARCHAR(20),
@tr_features_year NUMERIC(4),
@tr_features_description VARCHAR(15),
@tr_features_value VARCHAR(15),
@tr_features_feature_id INT
SELECT @tr_features_name=(SELECT name FROM INSERTED)
SELECT @tr_features_year=(SELECT year FROM INSERTED)
SELECT @tr_features_description=(SELECT description FROM INSERTED)
SELECT @tr_features_value=(SELECT value FROM INSERTED)
SELECT @tr_features_feature_id=(SELECT id FROM feature WHERE description = @tr_features_description AND value = @tr_features_value)
BEGIN
PRINT CONVERT(varchar(100),@tr_features_feature_id) + @tr_features_description + @tr_features_value + CONVERT(varchar(100),@tr_features_name) + @tr_features_year
INSERT INTO features VALUES(@tr_features_name,@tr_features_year,@tr_features_id)
END
我希望能够执行以下类型的插入,因此您可以使用该表的辅助键(和) id
,而不是使用表的(自动生成的)。feature
value
description
INSERT INTO features(name,year,descripition,value) VALUES('Malibu', 2012, 'colour', 'black');