質問

I am having a problem adding a foreign key constraint to SQL 2008 that is based on a composite primary key in another table. I have followed some directions based on a few posts on here, but haven't been able to get it to work.

I have two tables:

CREATE TABLE [Staging].[ActivityLog](
    [ActivityLogId] [int] IDENTITY(1,1) NOT NULL,
        ...
    [ActivityLogType] [varchar](10) NOT NULL,
    [ActivityLogSubType] [varchar](10) NOT NULL,
CONSTRAINT [PK_ActivityLog] PRIMARY KEY CLUSTERED 
(
    [ActivityLogId] ASC
))

and

CREATE TABLE [Staging].[ActivityLogTypeSubType](
    [ActivityLogType] [varchar](10) NOT NULL,
    [ActivityLogSubType] [varchar](10) NOT NULL,
CONSTRAINT [PK_ActivityLogTypeSubType] PRIMARY KEY CLUSTERED 
(
    [ActivityLogType] ASC,
    [ActivityLogSubType] ASC
))

GO

I am trying to add a foreign key like this:

ALTER TABLE Staging.ActivityLog
    ADD CONSTRAINT FK_ActivityLog_ActivityLogTypeSubType
    FOREIGN KEY(ActivityLogType, ActivityLogSubType)
    REFERENCES Staging.ActivityLogTypeSubType(ActivityLogType, ActivityLogSubType)

I get this error:

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint   "FK_ActivityLog_ActivityLogTypeSubType". The conflict occurred in database "HMDB_DEV", table "Staging.ActivityLogTypeSubType".

I have verified that this FK doesn't already exist.

I apologize for the lengthy post. Any help would be greatly appreciated.

Thanks, James

役に立ちましたか?

解決

Have you verified data to match FK logic?

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top