如何使用 table 中的触发器更新特定列和行

How to update a specific column and row with a trigger in a table

所以我有这个table

CREATE TABLE [dbo].[DailyParkReport] (
[Id]                  INT        IDENTITY (1, 1) NOT NULL,
[Date]                DATE       NOT NULL,
[InchesPrecipitation] FLOAT (53) NOT NULL,
[NumVisitors]         INT        NOT NULL,
[Rainout]             BIT        NOT NULL,
[Temperature]         FLOAT (53) NOT NULL,
CONSTRAINT [PK_DailyParkReport] PRIMARY KEY CLUSTERED ([Id] ASC)
);

并且我想设置一个触发器,每当 InchesPrecipitation 大于 4 时它使 Rainout 值 1 表示真,如果 InchesPrecipitation 小于 4 那么它使 Rainout 值为 0。所有这些都应该更新相同 table.

中的行

到目前为止我拥有的触发器是:

CREATE TRIGGER tr_weather_ForInsertUpdate 
ON [dbo].[DailyParkReport]
FOR INSERT, UPDATE
AS
BEGIN
    SET NOCOUNT ON
    IF (Select InchesPrecipitation FROM INSERTED) > 4

    UPDATE DailyParkReport
    SET Rainout = 1
    WHERE Rainout = 0

    ELSE

    UPDATE DailyParkReport
    SET Rainout = 0
    WHERE Rainout = 1

END

我 运行 遇到的问题是,每当触发触发器时,它都会更新 table 中的每一行,而我只希望它更新该特定行。

我已通过将触发器更新为以下

来解决问题
CREATE TRIGGER tr_weather_ForInsertUpdate 
ON [dbo].[DailyParkReport]
FOR INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON
IF (Select InchesPercipitation FROM INSERTED) > 4

    UPDATE d SET Rainout = 1
    FROM dbo.DailyParkReport AS d
    WHERE EXISTS (SELECT 1 FROM inserted WHERE Id = d.Id)

ELSE

    UPDATE d SET Rainout = 0
    FROM dbo.DailyParkReport AS d
    WHERE EXISTS (SELECT 1 FROM inserted WHERE Id = d.Id)

END
CREATE TRIGGER tr_weather_ForInsertUpdate
ON [dbo].[DailyParkReport]
FOR INSERT, UPDATE
AS
BEGIN
    SET NOCOUNT ON

    UPDATE DailyParkReport
        SET Rainout = CASE WHEN i.InchesPrecipitation >= 4 THEN 1 ELSE 0 END
    FROM
        DailyParkReport a
        INNER JOIN inserted i ON i.Id = a.Id
END

一个选项是 computed column... 它似乎很适合这里。当然,它确实有缺点。

create table #DailyParkReport 
([Id]                 INT        IDENTITY (1, 1) NOT NULL,
[Date]                DATE       NOT NULL,
[InchesPrecipitation] FLOAT (53) NOT NULL,
[NumVisitors]         INT        NOT NULL,
[Rainout]             as case when [InchesPrecipitation] >= 4 then 1 else 0 end,
[Temperature]         FLOAT (53) NOT NULL,
CONSTRAINT [PK_DailyParkReport] PRIMARY KEY CLUSTERED ([Id] ASC))

GO


insert into #DailyParkReport
values
(getdate(),3,1,98.6)
,(getdate(),5,1,98.6)

select * from #DailyParkReport

update #DailyParkReport
set InchesPrecipitation = 6 where Id = 1

select * from #DailyParkReport

drop table #DailyParkReport