在insert中添加额外的列而不是触发器

时间:2015-06-08 14:58:59

标签: sql sql-server tsql triggers

编辑1:基本上我想做 当用户只有col1和col2时,INSERT INTO用户(col1,col2,col3),col3不存在。

我有一个表 UsersAddresses ,有两个int字段" User"和"地址"这会将我的表用户绑定到另一个表地址。我需要审核对用户所做的任何更改,以便我的用户上的触发器工作正常,对我的Users表所做的任何更改都会在审计表中创建一行。

问题是如果我向用户添加地址,我还需要触发相同的触发器。所以我在UsersAddresses上创建了一个触发器,用于更新Users表。但是我需要有modifierId(知道谁想要做出这个改变)所以我想我应该改变我在UsersAddresses中插入的方式来添加这个Id。我尝试了以下内容,添加了一个假的" ModifierId"但正如预期的那样,我得到了#34;无效的列名"当我尝试添加此触发器时。 你知道我应该怎么做吗?

值得庆幸的是

CREATE TRIGGER UpdateUser 
ON [dbo].[UsersAddresses] 
INSTEAD OF INSERT 
AS
DECLARE @User INT;
DECLARE @Address INT;
DECLARE @ModifierId INT;

SELECT @User = [User] FROM inserted;
SELECT @Address = [Address] FROM inserted;
SELECT @ModifierId = [ModifierId] FROM inserted;

INSERT INTO [UsersAddresses]([User], [Address])
VALUES (@User, @Address);

UPDATE [Users]
SET [CreatorId] = @ModifierId
WHERE [Id] = @User;

修改解决方案:致Michael的积分 将context_info与过程一起使用。:

CREATE TABLE [dbo].[UsersAddresses] (
    [User]    INT NOT NULL,
    [Address] INT NOT NULL,
    CONSTRAINT [PK_UsersAddresses] PRIMARY KEY CLUSTERED ([User] ASC, [Address] ASC),
    CONSTRAINT [FK_ToUser] FOREIGN KEY ([User]) REFERENCES [dbo].[Users] ([Id]),
    CONSTRAINT [FK_ToAddress] FOREIGN KEY ([Address]) REFERENCES [dbo].[Addresses] ([Id])
);



GO
CREATE TRIGGER [ChangeToUsersAddresses]
    ON [dbo].[UsersAddresses]
    FOR DELETE, INSERT, UPDATE
    AS
    BEGIN
    IF ( (SELECT COUNT(*) FROM inserted) > 1)
      THROW 51000, 'To many records', 1

     DECLARE @UserId INT;
     IF (SELECT [User] FROM inserted) IS NOT NULL
     SELECT @UserId = [User] FROM inserted
     ELSE 
     SELECT @UserId = [User] FROM deleted
     INSERT INTO [Audit_Users](UserId,ActiveDirectory,FirstName,LastName,Type,Status,ModifierId,Date)
     SELECT [Id], [ActiveDirectory], [FirstName], [LastName], [Type], [Status], [dbo].GetUserContext(), GETDATE()
      FROM [dbo].[Users] WHERE [Id] = @UserId

  INSERT INTO [Audit_UsersAddresses]([User], [Address])
  SELECT @@IDENTITY, [Address]
  FROM [UsersAddresses]
  WHERE [User] = @UserId;

END;

插入中使用的GetUserContext():

CREATE FUNCTION [dbo].[GetUserContext] ()
RETURNS INT
AS
BEGIN
    RETURN COALESCE(CONVERT(INT, CONTEXT_INFO()), 0)
END

最后是设置上下文的过程。

CREATE PROCEDURE [dbo].[SetUserContext]
    @userId INT
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @context VARBINARY(128)
    SET @context = CONVERT(BINARY(128), @userId)

    SET CONTEXT_INFO @context
END

0 个答案:

没有答案