我有2个桌子House和AlarmInstall ... 我需要创建一个触发器,以便在我的警报安装表中插入uninstallDate(相异然后为Null)时,在房屋表中将布尔属性“ isInstaled”更新为false。 在SQL Server中触发时,我有点菜鸟。任何帮助将不胜感激!!!
这是2张桌子
[dbo].[AlarmInstall](
[AlarmInstallId] [int] IDENTITY(1,1) NOT NULL,
[HouseId] [int] NOT NULL,
[InstallDate] [date] NOT NULL,
[uninstallDate] [date] NOT NULL,
[Model] [nchar](10) NOT NULL,
[dbo].[House](
[HouseId] [int] IDENTITY(1,1) NOT NULL,
[StreetId] [int] NOT NULL,
[DoorNr] [nchar](10) NOT NULL,
[CityId] [int] NOT NULL,
[IsInstalled] [bit] NULL,
两个表都通过HouseId关联,HouseId在House Table中为PK,而在AlarmInstall中为FK
尝试使用此触发器,但我的所有房屋均被标记为真!!! 开始
CREATE TRIGGER STATECHANGE
ON dbo.AlarmInstall
AFTER INSERT, UPDATE
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
update dbo.House SET IsInstalled=1
From dbo.AlarmInstall a
inner join inserted i on a.HouseId=i.HouseId
and i.InstallDate is not null
END
答案 0 :(得分:0)
我认为这可以帮助:https://www.mssqltips.com/sqlservertip/4024/sql-server-trigger-after-update-for-a-specific-value/
您还可以使用带有以下定义的isInstalled计算字段:
<main></main>
但是我看不到像这样创建它(或使用触发器)的价值,因为当您没有此字段时,您总是可以在查询中计算它:
CREATE TABLE House(
HouseId int NOT NULL,
[...]
uninstallDate date NULL,
isInstalled bit AS CASE WHEN uninstallDate IS NULL THEN 0 ELSE 1 END
//已添加到原始答案
SELECT
HouseId,
[...]
uninstallDate,
CASE WHEN uninstallDate IS NULL THEN 0 ELSE 1 END AS isInstalled
FROM
House