0

我有两个相互关联的表 (featurefeatures),我想让开发人员对id一个表 ( feature) 拥有的 (主键) 透明。因此,为了插入一个表(features),您不必放入另一个表idfeature),您可以使用另一个表具有的辅助键。这是我的代码:

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,而不是使用表的(自动生成的)。featurevaluedescription

INSERT INTO features(name,year,descripition,value) VALUES('Malibu', 2012, 'colour', 'black');
4

1 回答 1

0

我遵循@adam 所说的,这就是结果

CREATE PROCEDURE [dbo].procedure_insert_features 
@pr_car_name VARCHAR(20) = NULL,
@pr_car_year NUMERIC(4) = NULL,
@pr_feature_description VARCHAR(15),
@pr_feature_value VARCHAR(15)
AS
SET NOCOUNT ON
BEGIN
DECLARE @pr_feature_id AS INTEGER
    SET @pr_feature_id = (SELECT ID FROM [automobile].[dbo].[feature] WHERE description = @pr_feature_description AND value = @pr_feature_value);
    -- PRINT @pr_feature_id
    IF @pr_feature_id IS NOT NULL
        BEGIN
            INSERT INTO [automobile].[dbo].available_features VALUES(@pr_car_name,@pr_car_year,@pr_feature_id);
    END
ELSE
    BEGIN
        RAISERROR ('ID NOT FOUND, PLEASE CHECK SPELLING', 10,1);
    END
END
于 2013-04-19T20:41:30.930 回答