2013-05-09 128 views
0

是否可以使日期時間數據類型的外鍵? 我試試這個,但我得到了錯誤信息: Msg 1776,Level 16,State 0,Line 1 引用表'penduduk'中沒有與外鍵'tgllahir'中的引用列表匹配的主鍵或候選鍵。 消息1750,級別16,狀態0,行1 無法創建約束。查看以前的錯誤。指向datetime的外鍵

我用這個查詢

父表:

create table penduduk (
no int identity(1,1), 
noktp char(11) primary key, 
nama varchar(20), 
tgl_lahir datetime NOT NULL, 
namahari varchar(20), 
tgl int, 
bulan int, 
namabulan varchar(20), 
tahun int, 
umur int 
) 

CREATE TABLE tua(
noktp CHAR(11) PRIMARY KEY, 
tgl_lahir datetime NOT NULL CONSTRAINT tgllahir FOREIGN KEY REFERENCES penduduk(tgl_lahir), 
FOREIGN KEY(noktp) REFERENCES penduduk(noktp), 
) 
+0

你引用的圖阿table.but tgl_lahir penduduk(tgl_lahir)未在penduduk表的主鍵 – Rohan 2013-05-09 12:59:17

回答

0

試試這個:

create table penduduk (
no int identity(1,1), 
noktp char(11) primary key, 
nama varchar(20), 
tgl_lahir datetime NOT NULL unique, 
namahari varchar(20), 
tgl int, 
bulan int, 
namabulan varchar(20), 
tahun int, 
umur int 
) 

CREATE TABLE tua(
noktp CHAR(11) PRIMARY KEY, 
tgl_lahir datetime NOT NULL CONSTRAINT tgllahir FOREIGN KEY REFERENCES penduduk(tgl_lahir), 
FOREIGN KEY(noktp) REFERENCES penduduk(noktp), 
) 
5

您只能使用一個列作爲一個外鍵約束的引用,如果它是一個合適的人選鍵。

從聯機叢書:

一個外鍵約束不必只鏈接到另一個表中的PRIMARY KEY 約束;它也可以定義爲在另一個表中引用 UNIQUE約束的列。

參見Foreign Key Constraints

在你的情況下,tgl_lahir既不是唯一的也不是主要的,所以不能在你的外鍵約束中使用。

如果您將唯一約束添加到tgl_lahir它應該工作;這對你的數據是否可行是真正的問題。