0

There are already posts, for example this one, which state that "naive" inheritance in SQL, namely using one table per class level, is a common thing. Example

create table parent
( id integer primary key
, more-parent-attributes
);

create table child
( id integer primary key references parent(id) on delete cascade
, more-child-attributes
);

My question is only how to insert a child in an idiomatic ANSI SQL way into the table. The foreign key constraint makes the requirement that we first insert a new row into parent and then a new row into child, using the id of the parent row. I don't know how to do this (get this id) safely and portably, and using only one request. Hint: I'm rather a beginner and don't know imperative SQL programming--just in case there is an obvious imperative solution.

4

3 に答える 3

0

私は結局似たようなことをしました。Parentを取得するには、 に挿入できる特定のデータが必要ですId。これをある種のアプリケーションで使用している場合は、GUID. 私のアプリケーションでは、一意の値を生成することがわかっているソース列の連結を使用しました。

CREATE TABLE Parent
(
     Id INT IDENTITY NOT NULL PRIMARY KEY
    ,SourceId VARCHAR(50) NOT NULL
);

CREATE TABLE Child
(
     ParentId INT NOT NULL REFERENCES Parent (Id)
    ,Data VARCHAR(20)
);

-- Some procedure inserts the unique value
INSERT INTO Parent (SourceId) VALUES ('UNIQUE VALUE');

-- Another procedure inserts data using the unique value
DECLARE @Id INT;

SELECT @Id = Id FROM Parent WHERE SourceId = 'UNIQUE VALUE';

INSERT INTO Child (ParentId, Data) VALUES (@Id, 'Some Data');
于 2013-09-06T12:53:35.167 に答える
0

Scope_Identity() はあなたが探しているものです:

DECLARE @Id INT

INSERT INTO parent (more-parent-attributes) values (.....)
SET @Id = Scope_Identity()

INSERT INTO child (parent(id), more-child-attributes) SELECT @Id, ....more-child-attributes

Scope_Identity() は、同じスコープ内の ID 列を返します。これは、親キーが ID 列である必要があることを意味します。

id  int IDENTITY(1,1)PRIMARY KEY

これは、親キーIDを決定している場合と同じだと思います。子挿入にも同じものを使用します。

于 2013-09-06T12:51:18.493 に答える
0

2 つの挿入を実行する必要があります。

最初の挿入は親テーブルに行を追加し、2 番目の挿入は子テーブルに行を追加します。

2 つの挿入操作を同じトランザクションにグループ化できます。

親テーブルに挿入された正しい ID を取得するには、親から選択 ID を取得する必要があります。

以下に表示:

ステップ1:

INSERT INTO parent (id, more att) values (your ID, other values)

ID 値に注意してください。newid() (Sql サーバー) uuid() (mySql) または自動インクリメンタル整数フィールドを使用できます

ステップ2:

機能キーを使用して親テーブルにクエリを実行し、キーを取得します。

SELECT id FROM parent where functional_key satisfacted

たとえば、従業員のリストを親テーブルに格納する場合、機能キーは登録番号にすることができます。

したがって、クエリは次のようになります。

SELECT id FROM parent WHERE register_no = 'YOUR_REGISTER_NUMBER'

ステップ 3:

INSERT INTO child (id, fk_parent, other fields) values(id, fk_parent, other fields)

fk_parent フィールドは、ステップ 2 の結果で評価する必要があります。

このステップでは、次のことができます。

値 fk_parent を変数で指定するか、insert ステートメントでサブクエリ (手順 2) を使用できます。

于 2013-09-06T12:44:02.827 に答える