CREATE TABLE t1 (
idt1 numeric(18, 0) IDENTITY(1,1) NOT NULL,
valt1 varchar(50) NOT NULL,
CONSTRAINT PK_t1 PRIMARY KEY CLUSTERED (
idt1 ASC
));
CREATE TABLE t2 (
idt2 numeric(18, 0) IDENTITY(1,1) NOT NULL,
refidt1 numeric(18, 0) NOT NULL,
valt2 varchar(50) NOT NULL,
CONSTRAINT PK_t2 PRIMARY KEY CLUSTERED (
idt2 ASC
));
ALTER TABLE t2 WITH CHECK ADD CONSTRAINT FK_t2_t1 FOREIGN KEY(refidt1) REFERENCES t1 (idt1);
go
CREATE VIEW v1
WITH SCHEMABINDING, VIEW_METADATA
AS
SELECT dbo.t1.idt1, dbo.t1.valt1, dbo.t2.valt2
FROM dbo.t1 INNER JOIN
dbo.t2 ON dbo.t2.refidt1 = dbo.t1.idt1;
go
CREATE trigger [tg_v1_ins] on [v1]
instead of insert
as
declare @newid as numeric;
begin
select @newid = t1.idt1 from t1, inserted where t1.valt1 = inserted.valt1;
if @newid is null
begin
insert into t1 (valt1) select valt1 from inserted
set @newid = scope_identity()
end
insert into t2 (refidt1, valt2) select @newid, valt2 from inserted
end;
go
insert into v1 (valt1, valt2) values ('truc1', 'truc1.1');
insert into v1 (valt1, valt2) values ('truc1', 'truc1.2');
insert into v1 (valt1, valt2) values ('truc2', 'truc2.1');
insert into v1 (valt1, valt2) values ('truc2', 'truc2.2');
select * from t1;
select * from t2;
select * from v1;
|