I have two tables that have a 1:1 relationship and use IDENTITY
columns for their primary keys.
A view is joining both tables together to give the impression that all columns are really stored in one table.
For viewing purposes this is fine, but the view needs an INSTEAD OF INSERT
trigger as well.
How do you write such a trigger that splits the column values across both tables?
Note: There is no candidate key other than the identity column in the parent table. Otherwise this question may help:
INSERT INTO View, INSTEAD OF Trigger, Identity, multiple tables?
(There is also a possible solution that declares a variable for every field in an answer of that question.)
Simplified schema (I left out PKEYs, FKEYs, COLLATIONS, etc.):
CREATE TABLE
[dbo].[parent]
(
[parent_id] INT IDENTITY(1,1)
, [name] NVARCHAR(100)
)
CREATE TABLE
[dbo].[child]
(
[parent_id] INT NOT NULL
, [child_id] INT IDENTITY(1,1)
, [name] NVARCHAR(100)
)
GO
CREATE VIEW
[dbo].[parent_child]
AS
SELECT
par.[parent_id]
, par.[name] AS "parent_name"
, chi.[child_id]
, chi.[name] AS "child_name"
FROM
[dbo].[parent] par
LEFT OUTER JOIN
[dbo].[child] chi
ON
chi.[parent_id] = par.[parent_id]
GO
The trigger template:
CREATE TRIGGER
[dbo].[parent_child_instead_of_insert]
ON
[dbo].[parent_child]
INSTEAD OF INSERT
AS
BEGIN
-- Implementation here
END
GO
Example data:
INSERT INTO
[dbo].[parent_child]
(
[parent_name]
, [child_name]
)
SELECT
'parent1'
, 'child1'
UNION
SELECT
'parent2'
, 'child2'