Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble using an equal sign in SQL trigger

This is my table:

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
);

I wrote a trigger to avoid redundancy:

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

But as this part of the code does not work, redundancy occurs:

(A.ProfileId = B.ProfileId)

Because after deleting this section, the operation is performed correctly. But this condition must be checked.

like image 354
M.R.T Avatar asked Feb 26 '26 18:02

M.R.T


1 Answers

Using my psychic skills, I suspect that you have ProfileId values that are null, and in SQL the expression null = null is not true, but your logic requires it to be true.

Try this:

AND (A.ProfileId = B.ProfileId OR (A.ProfileId IS NULL AND B.ProfileId IS NULL))
like image 54
Bohemian Avatar answered Feb 28 '26 06:02

Bohemian