create table tab(id int identity,task_id int,task_descp varchar(10),task_code varchar(10))
insert into tab values(7,'BUS','B')
insert into tab values(3,'CAR','C')
create table tab_detail( task_descp varchar(10),task_code varchar(10),color varchar(10))
create trigger tab_trigger on tab for insert as
declare @task_descp varchar(10)
declare @task_code varchar(10)
declare @task_id int
set @task_descp=i.task_descp from inserted i
set @task_code=i.task_code from inserted i
set @task_id=i.task_id from inserted i
if(@task_id=7)
insert into tab_detail values(@task_descp,@task_code,'BLUE')
if(@task_id=3)
insert into tab_detail values(@task_descp,@task_code,'GREEN')
go
我想为表tab
创建一个触发器,如果我根据task_id
列插入记录,则必须将记录插入到另一个表tab_detail
中。
执行此操作时出现此错误:
关键字'from'
附近的语法不正确
答案 0 :(得分:2)
而不是:
set @task_descp=i.task_descp from inserted i
试试这个:
select @task_descp=i.task_descp from inserted i
或者你可以这样做:
create trigger tab_trigger on tab for insert as
insert into tab_detail
select task_descp, task_code, case @task_id when 7 then 'BLUE' else 'GREEN' end
from inserted
where taskid in (7,3)
go
答案 1 :(得分:1)
将SET更改为SELECT。此外,inserted是记录集,而不是单个值。修复代码问题仍可能导致运行时问题!
此代码适用于记录信息集。
CREATE TRIGGER tab_trigger ON tab FOR INSERT AS
BEGIN
-- nothing to do?
IF (@@rowcount = 0) RETURN;
-- do not count rows
SET NOCOUNT ON;
-- inserted data
INSERT INTO tab_detail
SELECT
i.task_descp,
i.task_code,
CASE i.taskcode
WHEN 7 THEN 'BLUE'
WHEN 3 THEN 'GREEN'
ELSE ''
END
FROM inserted i
WHERE i.task_code in (3, 7)
END
GO