我收到错误:
Msg 213,Level 16,State 1,Procedure CUSTOMER_DELETE,第37行
列名或提供的值数与表定义不匹配
尝试创建此触发器时:
==> del *38001801.csv
==> d:\bat\so\38001801.bat
==> d:\bat\so\38001801.bat
==> d:\bat\so\38001801.bat
==> type *38001801.csv
f38001801.csv
24.06.2016;13:41:57,53;1
24.06.2016;13:42:19,10;11
24.06.2016;13:42:31,08;4
s38001801.csv
24.06.2016;13:42:00,11;1
24.06.2016;13:42:22,12;2
24.06.2016;13:42:34,13;1
==>
答案 0 :(得分:0)
即时错误是因为您的表Customer
显然拥有的列数多于您提供的两个列。您应始终明确定义要插入的列:INSERT INTO dbo.Customer(CustomerNo, Status) VALUES (@CustNo, 'Deleted');
...
但话又说回来:当你删除一个客户时 - 你真的想在客户表中插入一个新行吗?我怀疑您更有可能想要使用新值更新现有(已删除)行 - 请使用UPDATE
语句。
但更深问题是你的触发器有 MAJOR 设计缺陷:你似乎认为它每次被称为一次 - 那是不的情况。触发器会在每个语句时触发,因此如果导致此触发器的DELETE
语句触发删除25行,则会触发触发器,但是Deleted
伪表将包含25行。您的代码将选择哪25行中的哪一行?这是非确定性的,你会得到一行,你将忽略所有其他行。您需要重写触发器才能将其考虑在内!
所以把它们放在一起,我假设你真正想要的东西是这样的:
CREATE TRIGGER [DBO].[CUSTOMER_DELETE]
ON [dbo].[CUSTOMER]
AFTER DELETE
AS
BEGIN
SET NOCOUNT ON;
-- ONE, single nice set-based UPDATE statement to update
-- the "Status" column for those rows that were deleted by
-- your DELETE statement
UPDATE dbo.Customer
SET Status = 'Deleted' -- adapt to what your column is really called here!
FROM Deleted d
WHERE dbo.Customer.CustomerNo = d.CustomerNo
END