我的表Employee
和EmployeeUpdate
定义如下:
CREATE TABLE [dbo].[tblemployee](
[id] [int] NULL,
[name] [nchar](10) NULL,
[salary] [int] NULL,
[gender] [nchar](10) NULL,
[departmentid] [int] NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[tbl_employee_forinsert](
[id] [int] NULL,
[auditdata] [nchar](10) NULL
) ON [PRIMARY]
数据:
select * from employee
id name salary gender departmentid
1 jhon 5000 male 3
2 mike 3400 male 2
3 pam 6000 female 1
4 todd 4800 male 4
5 sara 3200 female 1
6 ben 4800 male 3
101 ram 50050 male 33
102 ram 50050 male 33
我想使用DML触发器在EmployeeUpdate
中插入行,我使用此代码:
create trigger tr_tbl_employee_forinsert
on tblemployee
for insert
as
begin
declare @id int
select @id = id from inserted
insert into [tbl_employee_forinsert]
values ('New employee with id = ' + cast (@id as nvarchar(5)) + ' is added at '+ cast ( Getdate () as nvarchar(20)))
end
我遇到了这个错误:
消息213,级别16,状态1,过程tr_tbl_employee_forinsert,行 9列名称或提供的值数与表不匹配 定义
答案 0 :(得分:0)
这应该有效:
create trigger tr_tbl_employee_forinsert
on tblemployee for insert as
begin
insert into [tbl_employee_forinsert] (id, auditdata)
select id, 'New employee with id = ' + cast (id as nvarchar(5)) + ' is added at '+ cast (Getdate () as nvarchar(20))
from inserted
end
虽然你的表只能将nchar(10)存储到auditdata中,所以你也必须修复它
答案 1 :(得分:0)
由于您已使用两列定义了表:
CREATE TABLE [dbo].[tbl_employee_forinsert](
[id] [int] NULL,
[auditdata] [nchar](10) NULL
) ON [PRIMARY]
您必须为两列提供值,或在insert
语句中指定要插入的列。
但是,代码还有两个更严重的问题:
1.您不能select @id = id from inserted
,因为插入的虚拟表包含一组数据,而不是单个项目。
2.您试图插入比列(声明为nchar(10)
)更多的字符有空间,因此您需要扩展列。
假设您希望在id列中插入员工的ID,您想要的触发器可能是这样的:
create trigger tr_tbl_employee_forinsert
on tblemployee for insert as
begin
insert into [tbl_employee_forinsert] (id, auditdata)
select i.id, 'New employee with id = ' + cast (i.id as nvarchar(5)) + ' is added at ' + cast (Getdate () as nvarchar(20)))
from inserted i
end
在查询中你提到了一个表EmployeeUpdate
,但是在定义中你有一个表tbl_employee_forinsert
,我想这是你所引用的表,所以如果它不匹配则更改名称