I'm trying to create 2 tables in one script. The first is an image table with a primary key and the second is an article table with a foreign key linked to the image table id. Code:
IF NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE 'Image')
CREATE TABLE [Image]
(
[ImageId] INT IDENTITY(1,1) NOT NULL,
[FileName] NVARCHAR(20) NOT NULL,
[ImageData] VARBINARY(MAX) NOT NULL,
CONSTRAINT PK_ImageId PRIMARY KEY CLUSTERED (ImageId ASC)
ON [PRIMARY]
)
IF NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE 'Article')
CREATE TABLE Article
(
ArticleId INT IDENTITY(1,1) NOT NULL,
CreatedAt DATE NOT NULL
CONSTRAINT D_ArticleDate DEFAULT GETDATE(),
Title NVARCHAR(20) NOT NULL,
Body NVARCHAR(MAX) NOT NULL,
MainImageId INT NULL,
CONSTRAINT PK_ArticleId PRIMARY KEY CLUSTERED (ArticleId ASC)
ON [PRIMARY],
CONSTRAINT FK_MainImageId FOREIGN KEY (MainImageId) REFERENCES [Image] (PK_ImageId)
)
If I run the Image query it runs fine. If I then run the Article query it runs fine. If I run both queries in one go, I get the following error:
Foreign key 'FK_MainImageId' references invalid column 'PK_ImageId' in referenced table 'Image'.
Is there a way to do this in one script?