I have the following query that I try to execute:
DECLARE @SessionId UNIQUEIDENTIFIER = NEWID();
INSERT INTO [security].[EventLog] ([Id], [Created], [Updated], [Session],
[IdentityGlobalId], [EventType], [Description])
SELECT
NEWID(), GETUTCDATE(), NULL, @SessionId,
r.Id, 4 AS [Change], -- RoleRemoved
'Removed role: ' + CAST(ISNULL(r.Region,'') AS VARCHAR(8)) + ':'+ CAST(ISNULL(r.CustomerNumber,'') AS VARCHAR(8)) + ':' + CAST(ISNULL(r.RoleId,'') AS VARCHAR(8))
FROM
@toRemove r
But when I try that, I get the following error:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_EventLog_Identities_IdentityGlobalId". The conflict occurred in database "master", table "security.Identities", column 'GlobalId'.
I know that before data can be inserted, the value in the foreign key field must exist in the other table first, in this case the Identities-table. The thing is that when I look into the identities-table, I can see the value right there.
So why do I still get this error?
DDL for the tables:
CREATE TABLE [security].[Identities]
(
[GlobalId] [uniqueidentifier] NOT NULL,
[Created] [datetimeoffset](7) NULL,
[Updated] [datetimeoffset](7) NULL,
CONSTRAINT [PK_Identities]
PRIMARY KEY CLUSTERED ([GlobalId] 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
CREATE TABLE [security].[EventLog]
(
[Id] [uniqueidentifier] NOT NULL,
[Created] [datetimeoffset](7) NULL,
[Updated] [datetimeoffset](7) NULL,
[Session] [uniqueidentifier] NOT NULL,
[IdentityGlobalId] [uniqueidentifier] NOT NULL,
[EventType] [nvarchar](max) NOT NULL,
[Description] [nvarchar](max) NOT NULL,
[Published] [datetimeoffset](7) NULL,
CONSTRAINT [PK_EventLog]
PRIMARY KEY CLUSTERED ([Id] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [security].[EventLog] WITH CHECK
ADD CONSTRAINT [FK_EventLog_Identities_IdentityGlobalId]
FOREIGN KEY([IdentityGlobalId]) REFERENCES [security].[Identities] ([GlobalId])
ON DELETE CASCADE
GO
ALTER TABLE [security].[EventLog] CHECK CONSTRAINT [FK_EventLog_Identities_IdentityGlobalId]
GO