麻烦在SQL触发器中使用等号

时间:2018-01-01 23:13:36

标签: sql sql-server triggers

这是我的表:

CREATE TABLE [dbo].[tblVisitors] (
    [Id]        BIGINT         IDENTITY (1, 1) NOT NULL,
    [IP]        NVARCHAR (100) NOT NULL,
    [ProfileId] INT            NULL,
    [DateVisit] DATE           NOT NULL,
    [TimeVisit] TIME (0)       NOT NULL,
    [Browser]   NVARCHAR (50)  NOT NULL,
    [UserOS]    NVARCHAR (500) NOT NULL,
    CONSTRAINT [PK_tblVisitors] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [FK_tblVisitors_tblProfile] FOREIGN KEY ([ProfileId]) REFERENCES [dbo].[tblProfile] ([Id]) ON DELETE SET NULL
);

我写了一个触发器来避免冗余:

CREATE TRIGGER [dbo].[Trigger_tblVisitors_OnInsert]
ON [dbo].[tblVisitors]
INSTEAD OF INSERT
AS
BEGIN
    SET NoCount ON;
    DECLARE @C INT;

    SELECT * 
    INTO #TEMP 
    FROM inserted A 
    WHERE
        NOT EXISTS (SELECT * 
                    FROM tblVisitors B 
                    WHERE (A.IP = B.IP) 
                      AND (A.DateVisit = B.DateVisit) 
                      AND (A.ProfileId = B.ProfileId));

    IF (SELECT COUNT(*) FROM #TEMP) = 0
    BEGIN
        PRINT 'DUPLICATE RECORD DETECTED';
        ROLLBACK TRANSACTION;
        RETURN;
    END

    INSERT INTO tblVisitors (IP, ProfileId, DateVisit, TimeVisit, Browser, UserOS)
           SELECT IP, ProfileId, DateVisit, TimeVisit, Browser, UserOS 
           FROM #TEMP;
END

但由于这部分代码不起作用,因此会发生冗余:

(A.ProfileId = B.ProfileId)

因为删除此部分后,操作正确执行。但必须检查这个条件。

1 个答案:

答案 0 :(得分:1)

使用我的心理技能,我怀疑你有ProfileId null的值,而在SQL中表达式null = null不是true,但你的逻辑需要它成为true

试试这个:

AND (A.ProfileId = B.ProfileId OR (A.ProfileId IS NULL AND B.ProfileId IS NULL))