我需要将多个表更改为外键。我使用了命令
ALTER TABLE financial_transactions
ADD FOREIGN KEY (item_rental_id) REFERENCES transaction_id(item_rental_id);
表名为financial_transactions,列名为item_rental_id。它给我一个错误说:
外键' FK__financial__item ___ 46E78A0C'引用无效表格' transaction_id'。
我该如何解决这个问题?
答案 0 :(得分:0)
您必须提供第二个表名 两种方式都可以做到 1.添加没有名称的引用
ALTER TABLE financial_transactions
ADD FOREIGN KEY (item_rental_id) REFERENCES customer_rentals(item_rental_id);
2.添加名称为
的引用ALTER TABLE financial_transactions
ADD CONSTRAINT FK_Financial_Transactions_Customer_Rental_Item_Rental_ID
FOREIGN KEY (item_rental_id) REFERENCES Customer_rentals(item_rental_id);
答案 1 :(得分:0)
是的,这是创建外键的正确脚本
ALTER TABLE financial_transactions
ADD FOREIGN KEY (item_rental_id) REFERENCES customer_rentals(item_rental_id);
但是,如果您尝试在已包含数据的表上添加外键约束,则必须确保financial_transactions表中的item_rental_id也在customer_rentals表中。否则,您将出现参照完整性错误。
举例说明:
CREATE TABLE customer_rentals_1
(item_rental_id INT,
PRIMARY KEY (item_rental_id)
);
CREATE TABLE financial_transactions_1
(transaction_id INT,
item_rental_id INT,
PRIMARY KEY (transaction_id)
);
ALTER TABLE financial_transactions_1
ADD FOREIGN KEY (item_rental_id) REFERENCES customer_rentals_1(item_rental_id);
上述脚本将成功运行。
CREATE TABLE customer_rentals_2
(item_rental_id INT,
PRIMARY KEY (item_rental_id)
);
CREATE TABLE financial_transactions_2
(transaction_id INT,
item_rental_id INT,
PRIMARY KEY (transaction_id)
);
INSERT INTO financial_transactions_2
VALUES (1000, 9999);
ALTER TABLE financial_transactions_2
ADD FOREIGN KEY (item_rental_id) REFERENCES customer_rentals_2(item_rental_id);
但是,由于customer_rentals_2表中没有item_rental_id 9999,因此会出现以下错误
Msg 547, Level 16, State 0, Line 31
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__financial__item___76969D2E". The conflict occurred in database "TESTDB", table "dbo.customer_rentals_2", column 'item_rental_id'.