【问题标题】:Update columns of a row in trigger when values are 0当值为 0 时更新触发器中行的列
【发布时间】:2014-01-15 05:43:49
【问题描述】:

我在 SQL Server 2008 中有一个表。在网页中用 0 插入这些列

列:

id (identity)
enero (decimal)  --inserts 0 convert to null
febrero (decimal)--inserts 0 convert to null
marzo (decimal)  --inserts 0 convert to null
abril (decimal)  --inserts 0 convert to null
etc..


CREATE TRIGGER Pone
   ON  Rf_Egr_Meses
   AFTER   INSERT, UPDATE 
AS 
BEGIN
    --  
    SET NOCOUNT ON;

    --i don't know hoy compare if are 0 and what row 
  update Rf_Egr_Meses set ene=null , feb=null, mar=null where ()




END
GO

由于某些原因,我无法更改插入 0 的网页。

在一个表中,我想创建一个触发器,将值从 0 转换为 null(仅当值为 0 时)

有什么创建触发器的想法吗?

【问题讨论】:

  • 我创建了一个触发器,但我不知道如何更新插入的行并比较列是否为 0
  • 谢谢我编辑,对不起,我只是创建触发器我很新手

标签: sql-server sql-server-2008 tsql triggers


【解决方案1】:

尝试这样的事情 - 使用 NULLIF 函数,如果表达式为真,则返回 NULL

CREATE TRIGGER trgInsertNullIfZero
ON dbo.Rf_Egr_Meses
FOR INSERT
AS 
    UPDATE dbo.Rf_Egr_Meses
    SET 
        enero = NULLIF(i.enero, 0.0),
        febrero = NULLIF(i.febrero, 0.0),
        marzo = NULLIF(i.marzo, 0.0),
        abril = NULLIF(i.abril, 0.0)
            -- and so on, probably for all twelve months
    FROM 
        INSERTED i
    WHERE   
        dbo.YourTableNameHere.ID = i.ID

这将处理一次插入多行的多个插入。

您可以通过发出以下命令来尝试:

INSERT INTO dbo.Rf_Egr_Meses(enero, febrero, marzo, abril)
VALUES  (42.0, 0.0, 55.0, 0.0), (0.0, 17.0, 44.0, 49.0)

现在,如果您选择您的行,您应该会看到对于插入的第一行,您会得到两个 NULL(对于 febreroabril),其中提供了 0.0

【讨论】:

  • 谢谢你..你是大师
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-25
  • 2021-09-08
  • 1970-01-01
  • 2020-12-31
相关资源
最近更新 更多