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

时间:2018-04-24 17:56:24

标签: sql sql-server database database-trigger

所以我有这张桌子

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.所有这些都应该更新同一个表中的行。

到目前为止,触发器的内容是:

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

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

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

来解决问题
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

2 个答案:

答案 0 :(得分:3)

一个选项是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

答案 1 :(得分:1)

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