ArtistID
表中的Piece
列引用ArtistID
表中的Artist
。同样,LocationID
中的Piece
列引用LocationID
表中的GeographicLocation
。但是,两个外键引用都引发“与引用列不同的数据类型”错误。我在做什么错了?
CREATE TABLE dbo.Artist
(
ArtistID SMALLINT PRIMARY KEY IDENTITY,
LastName VARCHAR(50) NOT NULL,
FirstName VARCHAR(40) NOT NULL,
Nationality VARCHAR(10) NULL,
BirthYear SMALLINT NOT NULL CHECK(BirthYear <= 1980),
DeathYear SMALLINT NULL,
Sex CHAR(1) NOT NULL CHECK(Sex = 'F' OR Sex = 'M')
)
CREATE TABLE dbo.Piece
(
PieceID SMALLINT PRIMARY KEY IDENTITY(1, 5),
ArtistID SMALLINT NOT NULL
FOREIGN KEY REFERENCES Artist(ArtistID),
LocationID SMALLINT NOT NULL
FOREIGN KEY REFERENCES GeographicLocation(LocationID),
CommonName VARCHAR(100) NULL,
YearProduced TINYINT NULL,
Period VARCHAR(50) NULL,
Medium VARCHAR(35) NOT NULL,
Frame VARCHAR(35) NULL,
AppraisedValue MONEY NOT NULL,
AppraiserID SMALLINT NOT NULL
FOREIGN KEY REFERENCES Appraiser(AppraiserID)
)
CREATE TABLE dbo.GeographicLocation
(
LocationID SMALLINT PRIMARY KEY IDENTITY,
Country VARCHAR(25) NOT NULL,
City VARCHAR(50) NOT NULL
)
答案 0 :(得分:1)
我认为您在这里错过了一个表,这是计件表中的AppraiserID列,它引用了Appraisertable中的AppraiserID
因此,当我执行您的SQL时,我遇到以下错误:
外键'FK__Piece__Appraiser__322C6448'引用了无效的表'Appraiser'。
首先创建一个名为Appraiser的表,然后为这些列创建外键引用。
在SQL下面,我可以创建所有表和外键引用:
CREATE TABLE dbo.Artist
(ArtistID SMALLINT PRIMARY KEY IDENTITY,
LastName VARCHAR(50) NOT NULL,
FirstName VARCHAR(40) NOT NULL,
Nationality VARCHAR(10) NULL,
BirthYear SMALLINT NOT NULL CHECK(BirthYear <= 1980),
DeathYear SMALLINT NULL,
Gender CHAR(1) NOT NULL CHECK(Gender = 'F' OR Gender = 'M'))
CREATE TABLE dbo.GeographicLocation
(LocationID SMALLINT PRIMARY KEY IDENTITY,
Country VARCHAR(25) NOT NULL,
City VARCHAR(50) NOT NULL)
CREATE TABLE dbo.Appraiser
(AppraiserID SMALLINT PRIMARY KEY IDENTITY(1, 5),
AppraisedValue MONEY NOT NULL,
AppraisedName VARCHAR(100) NULL)
CREATE TABLE dbo.Piece
(PieceID SMALLINT PRIMARY KEY IDENTITY(1, 5),
ArtistID SMALLINT NOT NULL,
LocationID SMALLINT NOT NULL,
CommonName VARCHAR(100) NULL,
YearProduced TINYINT NULL,
Period VARCHAR(50) NULL,
Medium VARCHAR(35) NOT NULL,
Frame VARCHAR(35) NULL,
AppraisedValue MONEY NOT NULL,
AppraiserID SMALLINT NOT NULL)
ALTER TABLE dbo.Piece WITH CHECK ADD CONSTRAINT FK_Piece_ArtistID FOREIGN KEY(ArtistID)
REFERENCES dbo.Artist (ArtistID)
GO
ALTER TABLE dbo.Piece CHECK CONSTRAINT FK_Piece_ArtistID
GO
ALTER TABLE dbo.Piece WITH CHECK ADD CONSTRAINT FK_Piece_AppraiserID FOREIGN KEY(AppraiserID)
REFERENCES dbo.Appraiser (AppraiserID)
GO
ALTER TABLE dbo.Piece CHECK CONSTRAINT FK_Piece_AppraiserID
GO
ALTER TABLE dbo.Piece WITH CHECK ADD CONSTRAINT FK_Piece_LocationID FOREIGN KEY(LocationID)
REFERENCES dbo.GeographicLocation (LocationID)
GO
ALTER TABLE dbo.Piece CHECK CONSTRAINT FK_Piece_LocationID
GO