简体   繁体   中英

SQL Server : foreign key references invalid table

I'm not sure what I'm doing wrong, but I'm getting a foreign key references invalid table message telling me that dbo.ValueStream is an invalid table.

Edit : I originally posted my code in the incorrect order. Fixed in the edit to reflect the order it was done in SSMS

CREATE TABLE dbo.ValueStream 
(
    ValueStreamKey int IDENTITY(1,1) NOT NULL
        CONSTRAINT PK_ValueStream_ValueStreamKey PRIMARY KEY,
    ValueStream nvarchar(20),
)

CREATE TABLE dbo.NonConformance 
(
    NonConformanceKey int IDENTITY(1,1) NOT NULL
        CONSTRAINT PK_NonConformance_NonConformanceKey PRIMARY KEY,
    CustomerVendorKey int NOT NULL
        CONSTRAINT FK_NonConformance_CustomerVendorKey_CustomerVendor_CustomerVendorKey
            FOREIGN KEY REFERENCES dbo.CustomerVendor(CustomerVendorKey),
    ValueStreamKey int NOT NULL
        CONSTRAINT FK_NonConformance_ValueStream_Key_ValueStream_ValueStreamKey
            FOREIGN KEY REFERENCES dbo.ValueStream(ValueStreamKey),
    RepairOrder nvarchar(50) NOT NULL,
    WorkOrder nvarchar(8) NOT NULL,
    PartNumber nvarchar(50) NOT NULL,
    SerialNumber nvarchar(50) NOT NULL,
    PartDescription nvarchar(50) NOT NULL,
    InductionDate datetime NOT NULL,
    TriageStartDate datetime NOT NULL,
    TriageCompletionDate datetime NOT NULL,
    RequiresRRCA Bit NOT NULL,
    NonConformanceSummary nvarchar(max) NOT NULL
);

You are creating dbo.NonConformance first in the script that you have posted. You need to move the CREATE TABLE dbo.ValueStream statement so that it is created first, ensuring there is a GO statement still between the two CREATE TABLE statements.

As it stands you are trying to create a foreign key to a table that does not exist.

taking out the CONSTRAINT FK_NonConformance_CustomerVendorKey_CustomerVendor_CustomerVendorKey FOREIGN KEY REFERENCES dbo.CustomerVendor(CustomerVendorKey) (we don't have that one) and running the scripts seperately - first the first table and then the creation of the referencing table - this works for me. No code errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM