有两个表(info,info2),我已将它们连接起来并为它们创建一个视图(v_fullinfo)。我还在该视图上创建了一个触发器(t_1),该工作是将插入的数据插入另一个数据库的另一个表(tabinfo)。我已经阅读了#34;插入后#34;不适用于视图,我应该使用"而不是instert"。不幸的是,当我将数据插入表格时,#34; info"和" info2"它没有出现在" tabinfo"中。如何dinamicaly从该视图插入数据到另一个表?
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[info](
[id] [int] IDENTITY(1,1) NOT NULL,
[name] [nchar](10) NULL,
[lastname] [nchar](10) NULL,
[gender] [nchar](10) NULL
) ON [PRIMARY]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[info2](
[id] [int] IDENTITY(1,1) NOT NULL,
[country] [nchar](10) NULL,
[city] [nchar](10) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[info] ([id], [name], [lastname], [gender]) VALUES (1,
N'Johnny', N'English ', N'Male ')
INSERT [dbo].[info] ([id], [name], [lastname], [gender]) VALUES (2, N'John'
, N'Doe ', N'Male ')
INSERT [dbo].[info] ([id], [name], [lastname], [gender]) VALUES (3,
N'Susan', N'Stewart ', N'Female ')
INSERT [dbo].[info] ([id], [name], [lastname], [gender]) VALUES (4,
N'Frank', N'Moore ', N'Male ')
INSERT [dbo].[info] ([id], [name], [lastname], [gender]) VALUES (5, N'Jan'
, N'Kowalski ', N'Male ')
INSERT [dbo].[info2] ([id], [country], [city]) VALUES (1, N'USA ',
N'New York ')
INSERT [dbo].[info2] ([id], [country], [city]) VALUES (2, N'USA ',
N'Washington')
INSERT [dbo].[info2] ([id], [country], [city]) VALUES (3, N'UK ',
N'London ')
INSERT [dbo].[info2] ([id], [country], [city]) VALUES (4, N'Irland ',
N'Dublin ')
CREATE view [dbo].[v_fullinfo]
as
SELECT dbo.info.id, dbo.info.name, dbo.info.lastname,
dbo.info.gender, dbo.info2.country, dbo.info2.city
FROM dbo.info LEFT JOIN
dbo.info2 ON dbo.info.id = dbo.info2.id
create TRIGGER [dbo].[t_1]
ON [dbo].[v_fullinfo]
INSTEAD OF insert
AS
BEGIN
SET NOCOUNT ON;
if (select count(*) from inserted )>1
begin
raiserror ('nie mozesz',16,1)
rollback
end
declare @id int
declare @name nchar(10)
declare @lastname nchar(10)
declare @gender nchar(10)
declare @country nchar(10)
declare @city nchar(10)
select
@id=id,
@name=name,
@lastname=lastname,
@gender=gender,
@country=country,
@city=city
from inserted
insert [test2].[dbo].[tabinfo] (id, name, lastname,gender, country,
city)
values (@id, @name, @lastname,@gender, @country, @city)
end
`CREATE TABLE [dbo].[tabinfo](
[id] [int] NULL,
[name] [nchar](10) NULL,
[lastname] [nchar](10) NULL,
[gender] [nchar](10) NULL,
[country] [nchar](10) NULL,
[city] [nchar](10) NULL
) ON [PRIMARY]
`
答案 0 :(得分:2)
您的触发器在视图上,但您正在插入基础表,因此您的触发器未被触发。
在每个表格上放置一个AFTER UPDATE
触发器,或者将INSERT
更改为插入视图。
请注意,您的INSTEAD OF
触发器发生 而不是 预期的DML操作,即您的预期插入不会发生,您必须自己处理。例如,在视图上使用INSTEAD OF
时,当您插入视图时,您将需要获取这些值并执行您需要执行的基础表上的任何插入。