所以我有一张名为" person"在数据库test1中:
CREATE TABLE [dbo].[persons](
[ID] [int] IDENTITY(1,1) NOT NULL,
[LastName] [varchar](50) NULL,
[FirstName] [varchar](50) NULL,
[Job] [varchar](50) NULL,
[Extension] [char](10) NULL,
[EMail] [varchar](50) NULL,
[Dept] [int] NULL,
[MobileNumber] [char](10) NULL,
[District] [int] NULL,
[Status] [varchar](50) NULL,
[InOutStatus] [varchar](5) NULL,
[InOutDescr] [varchar](50) NULL,
[InOutDirections] [varchar](255) NULL,
[InOutReturn] [varchar](50) NULL,
[login] [varchar](50) NULL,
[StatusExpiry] [datetime] NULL
) ON [PRIMARY]
一张名为" Users"在数据库test2中:
CREATE TABLE [dbo].[Users](
[User_ID] [int] NOT NULL,
[Firstname] [nvarchar](50) NULL,
[Lastname] [nvarchar](50) NULL,
[Username] [nvarchar](50) NULL,
[Status] [nvarchar](50) NULL
) ON [PRIMARY]
我尝试做的是创建一个触发器,如果更新了人员表中的FirstName,LastName,login和/或Status列,则会在Users的相同列中更新相同的值表。这是我提出的触发器,但它不起作用:
ALTER TRIGGER [dbo].[UserUpdteTrig]
ON [dbo].[persons]
AFTER UPDATE
AS
BEGIN
DECLARE @uid int;
DECLARE @fname nvarchar(50);
DECLARE @lname nvarchar(50);
DECLARE @uname nvarchar(50);
DECLARE @stat nvarchar(50);
SELECT @fname = i.FirstName, @lname = i.LastName, @uname = i.login, @stat = i.Status
FROM inserted i
UPDATE [test2].[dbo].[Users]
SET Firstname = @fname , Lastname = @lname, Username = @uname, Status = @stat
FROM [test2].[dbo].[Users] u INNER JOIN inserted i ON u.User_ID = i.ID
END
我不断收到一条错误消息:更新和删除的行值不会使行唯一或者它们会改变多行,这两个表中的PK都是唯一的,并且PK不应该被改变
答案 0 :(得分:0)
你根本不需要任何变量,只需简单的更新即可。
ALTER TRIGGER [dbo].[UserUpdteTrig]
ON [dbo].[persons]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
UPDATE u
SET u.Firstname = i.FirstName
, u.Lastname = i.Lastname
, u.Username = i.Username
, u.[Status] = i.[Status]
FROM [test2].[dbo].[Users] u
INNER JOIN inserted i ON u.[User_ID] = i.ID
END