触发不触发

时间:2014-12-15 18:35:25

标签: sql-server triggers

根据下图,我有两张桌子

enter image description here

这是USERS TABLES

的sql脚本
USE [NewUser]
GO

/****** Object:  Table [dbo].[USERS]    Script Date: 15/12/2014 18:26:05 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[USERS](
    [FirstName] [varchar](50) NULL,
    [SureName] [varchar](50) NULL,
    [DOB] [date] NULL,
    [USID] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_USERS] PRIMARY KEY CLUSTERED 
(
    [USID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, 
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

对于ADDRESSES TABLE

USE [NewUser]
GO

/****** Object:  Table [dbo].[ADDRESSES]    Script Date: 15/12/2014 18:26:35 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[ADDRESSES](
    [AID] [int] IDENTITY(1,1) NOT NULL,
    [USID] [numeric](18, 0) NULL,
    [AddressLine1] [varchar](50) NULL,
    [AddressLine2] [varchar](50) NULL,
    [PostCode] [varchar](50) NULL,
 CONSTRAINT [PK_ADDRESSES] PRIMARY KEY CLUSTERED 
(
    [AID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
 ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

ALTER TABLE [dbo].[ADDRESSES]  WITH CHECK ADD  CONSTRAINT [FK_ADDRESSES_USERS]
FOREIGN     KEY([USID])
REFERENCES [dbo].[USERS] ([USID])
ON UPDATE CASCADE
ON DELETE SET NULL
GO

ALTER TABLE [dbo].[ADDRESSES] CHECK CONSTRAINT [FK_ADDRESSES_USERS]
GO

之后我使用

创建了TRIGGER
USE [NewUser]
GO
/****** Object:  Trigger [dbo].[autoupdate]    Script Date: 15/12/2014 18:33:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[autoupdate]
    ON [dbo].[USERS]
    AFTER INSERT, DELETE, UPDATE
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @TEMPID INT
    SET @TEMPID = (SELECT USID FROM INSERTED)
    UPDATE ADDRESSES
    SET USID = @TEMPID
END

TRIGGER的目的是在第一个表中添加或更新新行时立即在第二个表上插入UID。

但它没有做我期望它做的事情。

截图

USERS TABLE

enter image description here

ADDRESSES TABLE

enter image description here

来自表格USID

USERS和来自表格AID的{​​{1}}都有"身份设置为YESS"

2 个答案:

答案 0 :(得分:1)

我假设这是SQL Server,而不是MySql - 请删除冲突的RDBMS标记。

使用触发器,您需要处理设置数据 - INSERTEDDELETED伪列是表,而不是单行。

另外,假设您不打算更新用户的PK [USID],您不需要在触发器中处理UPDATE,只需要INSERT和DELETE,它看起来就像你已经决定用ON DELETE SET NULL处理用户删除一样,这会在地址中将USID外键设置为NULL。

所以这留下了INSERT - 我猜这里你只想为新用户插入一个空地址?:

ALTER TRIGGER [dbo].[autoupdate]
    ON [dbo].[USERS]
    AFTER INSERT
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO ADDRESSES(USID)
        SELECT USID FROM INSERTED i
        WHERE NOT EXISTS (SELECT 1 FROM ADDRESSES a WHERE a.USID = i.USID)
        AND i.USID IS NOT NULL;

END

答案 1 :(得分:0)

为了使您的触发按照您设计的方式执行任何操作,您需要在地址表中包含记录。一旦记录存在,当记录更新或插入Users表时,它的USID将被更新。