SQL Server外键引用

时间:2015-02-10 13:45:42

标签: sql sql-server database reference

CREATE TABLE users 
(
    id INTEGER PRIMARY KEY IDENTITY,
    name VARCHAR (128),
    email VARCHAR (128),
    pass VARCHAR (128),
    paid BIT,
    rank FLOAT,
    status INT,
    active BIT
);

CREATE TABLE books 
(
    id INTEGER PRIMARY KEY IDENTITY,
    FOREIGN KEY (owner) REFERENCES users (id),
    FOREIGN KEY (holder) REFERENCES users (id),
    name VARCHAR (128),
    author VARCHAR (128),
    year INTEGER,
    rank FLOAT,
    publisher VARCHAR (128)
);

错误列表:

  

Ms 1769,Level 16,State 1,Line 18
  外键'所有者'引用无效列'所有者'在引用表'书籍'。

     

Msg 1750,Level 16,State 0,Line 18
  无法创建约束。查看以前的错误。

3 个答案:

答案 0 :(得分:2)

您需要定义列以引用它们。您可以将定义全部放在一行中,如下所示:

CREATE TABLE books (
    id INTEGER PRIMARY KEY IDENTITY,
    owner INTEGER REFERENCES users(id),
    holder INTEGER REFERENCES users(id),
    name VARCHAR(128),
    author VARCHAR(128),
    year INTEGER,
    rank FLOAT,
    publisher VARCHAR (128)
);

答案 1 :(得分:1)

您必须申报var owner和holder
SQL SCRIPT:

CREATE TABLE books (
id INTEGER PRIMARY KEY IDENTITY,
ownder INTEGER,
holder INTEGER,
name VARCHAR (128),
author VARCHAR (128),
year INTEGER,
rank FLOAT,
publisher VARCHAR (128)
FOREIGN KEY (owner) REFERENCES users (id),
FOREIGN KEY (holder) REFERENCES users (id),
);

答案 2 :(得分:0)

CREATE TABLE users (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
name VARCHAR (128),
email VARCHAR (128),
pass VARCHAR (128),
paid BIT,
rank FLOAT,
status INT,
active BIT
);


CREATE TABLE books (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
FOREIGN KEY (owner) REFERENCES users (id),
FOREIGN KEY (holder) REFERENCES users (id),
owner INTEGER,
holder INTEGER,
name VARCHAR (128),
author VARCHAR (128),
year INTEGER,
rank FLOAT,
publisher VARCHAR (128)
);