设置外键 - 交易SQL

时间:2016-01-28 12:25:53

标签: sql-server tsql foreign-keys sql-server-2014 create-table

在分配外键时,我在SQL Server 2014中遇到以下tSQL问题。有人可以帮我理解什么是不正确的吗?谢谢 - JT

    create table dbo.tbl_Util_Cost
    (
    chr_Grade   nchar(10)    not null Primary Key,
    pct_Target  decimal(18, 2)  not null,
    mon_Cost_Per_Hour   money   not null,
    dec_Daily_Hours decimal(18, 1)  not null
    );

    create table dbo.tbl_Team_Details
   (
     num_Personal_Number    numeric(18, 0)  not null,
     chr_Name   nchar(30)    not null,
     chr_Employee_Grade nchar(10)    not null ,
     dt_Start_Date date not null,
     dt_End_Date date   not null,
     foreign key fk_Team_Details1  ( chr_Employee_Grade) references dbo.tbl_Util_Cost (chr_Grade)   
    );

我在外键上遇到以下错误 -

  

Msg 102,Level 15,State 1,Line 11语法不正确   'fk_Team_Details1'

请指教!

4 个答案:

答案 0 :(得分:1)

你的语法错了。 以下是正确语法的示例:

CONSTRAINT fk_Team_Details1 FOREIGN KEY(chr_Employee_Grade) 参考文献dbo.tbl_Util_Cost(chr_Grade)

更多信息:Create Foreign Key Relationships

答案 1 :(得分:0)

替换

foreign key fk_Team_Details1  
( chr_Employee_Grade) references dbo.tbl_Util_Cost (chr_Grade)

 constraint fk_Team_Details1  
 foreign key (chr_Employee_Grade) references dbo.tbl_Util_Cost (chr_Grade)

完整的脚本:

create table dbo.tbl_Util_Cost
(
chr_Grade   nchar(10)    not null Primary Key,
pct_Target  decimal(18, 2)  not null,
mon_Cost_Per_Hour   money   not null,
dec_Daily_Hours decimal(18, 1)  not null
);

create table dbo.tbl_Team_Details
(
 num_Personal_Number    numeric(18, 0)  not null,
 chr_Name   nchar(30)    not null,
 chr_Employee_Grade nchar(10)    not null ,
 dt_Start_Date date not null,
 dt_End_Date date   not null,
 constraint fk_Team_Details1  foreign key ( chr_Employee_Grade) references dbo.tbl_Util_Cost (chr_Grade)   
);

答案 2 :(得分:0)

在添加Foriegn Key时修改第二个表创建

  constraint fk_Team_Details1  foreign key  
 ( chr_Employee_Grade) references dbo.tbl_Util_Cost (chr_Grade)   

答案 3 :(得分:0)

你去吧

create table dbo.tbl_Util_Cost
(
chr_Grade   nchar(10)    not null Primary Key,
pct_Target  decimal(18, 2)  not null,
mon_Cost_Per_Hour   money   not null,
dec_Daily_Hours decimal(18, 1)  not null
);

create table dbo.tbl_Team_Details
(
 num_Personal_Number    numeric(18, 0)  not null,
 chr_Name   nchar(30)    not null,
 chr_Employee_Grade nchar(10)    not null ,
 dt_Start_Date date not null,
 dt_End_Date date   not null,
 constraint fk_Team_Details1  foreign key ( chr_Employee_Grade) references dbo.tbl_Util_Cost (chr_Grade)   
);