0

相互に関連する2つのテーブル(featureと)があり、1つのテーブル()が持つ(主キー)をfeatures開発者に透過的にしたいと思います。したがって、一方のテーブル()に挿入するために、もう一方のテーブル()を配置する必要はありません。もう一方のテーブルにある2次キーを使用できます。これが私のコードです:idfeaturefeaturesidfeature

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

次のタイプの挿入を実行できるようにしたいので、(自動的に生成される)テーブルのを使用する代わりにidfeatureこのテーブルの2次キー(valueおよびdescription)を使用できます。

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 に答える