Sql server 更新后触发器中的SQL Server插入
我是SQL Server新手,我正在尝试构建一个简单的更新触发器,每当列ceu_amount从零更新到大于零的任何数字时,它都会将一行写入临时表 通过使用PRINT语句,我知道变量包含执行INSERT语句的正确值,但没有插入行 你能帮忙吗Sql server 更新后触发器中的SQL Server插入,sql-server,Sql Server,我是SQL Server新手,我正在尝试构建一个简单的更新触发器,每当列ceu_amount从零更新到大于零的任何数字时,它都会将一行写入临时表 通过使用PRINT语句,我知道变量包含执行INSERT语句的正确值,但没有插入行 你能帮忙吗 CREATE TRIGGER [dbo].[TRG_Product_Function_Modified] ON [dbo].[Product_Function] AFTER UPDATE AS BEGIN SET NOCOUNT ON; --
CREATE TRIGGER [dbo].[TRG_Product_Function_Modified] ON [dbo].[Product_Function]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
--
-- Variable definitions
--
DECLARE @product_code_new as varchar(31)
DECLARE @product_code_old as varchar(31)
--
-- Check if the staging table needs to be updated.
--
SELECT @product_code_new = product_code FROM Inserted where ISNULL(ceu_amount,0) > 0;
SELECT @product_code_old = product_code FROM Deleted where ISNULL(ceu_amount,0) = 0;
IF @product_code_new IS NOT NULL
AND @product_code_old IS NOT NULL
INSERT INTO Product_Function_Staging VALUES (@product_code_new,CURRENT_TIMESTAMP);
END;
试试这个
CREATE TRIGGER [dbo].[Customer_UPDATE]
ON [dbo].[Customers]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
DECLARE @CustomerId INT
DECLARE @Action VARCHAR(50)
SELECT @CustomerId = INSERTED.CustomerId
FROM INSERTED
IF UPDATE(Name)
BEGIN
SET @Action = 'Updated Name'
END
IF UPDATE(Country)
BEGIN
SET @Action = 'Updated Country'
END
INSERT INTO CustomerLogs
VALUES(@CustomerId, @Action)
END
我觉得这部分代码很可疑
SELECT @product_code_new = product_code FROM Inserted where ISNULL(ceu_amount,0) > 0;
SELECT @product_code_old = product_code FROM Deleted where ISNULL(ceu_amount,0) = 0;
IF @product_code_new IS NOT NULL
AND @product_code_old IS NOT NULL
INSERT INTO Product_Function_Staging VALUES (@product_code_new,CURRENT_TIMESTAMP);
如果只更新了一行,那么如果有多个值,那么上面的操作就可以了。产品代码将默认为最后一个值
您可以将代码的上面部分更改为下面的部分
Insert into Product_Function_Staging
select product_code ,CURRENT_TIMESTAMP from inserted where product_code is not null
如果有多行更新为ceu_amount>0,则@product_code_new的值将不确定;如果多行更新为ceu金额NULL或等于0,则@product_code_old的情况类似。
您可以发布一些示例数据吗?我不会在触发器中使用类似的变量,因为触发的原因可能是对多行的更新,此时更新和删除的表中会有多行 我认为我们可以通过一个简单的查询更安全、更高效地进行此插入,尽管我假设您有一个唯一的密钥可以使用:
CREATE TRIGGER [dbo].[TRG_Product_Function_Modified] ON [dbo].[Product_Function]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO Product_Function_Staging
SELECT i.product_code, CURRENT_TIMESTAMP
FROM inserted i
JOIN deleted d ON i.product_code = d.product_code -- assuming product_code is unique
WHERE i.ceu_amount > 0 -- new value > 0
AND ISNULL(d.ceu_amount, 0) = 0; -- old value null or 0
END;
我不确定您需要在何处检查数据中的空值,因此我在where子句中做了一个最佳猜测。我建议对其进行编辑,以便它引用OPs表和列。另外,
如果update
不关心更新的值,只关心设置了列,因此我认为这无论如何都不会起作用。