在实现参照完整性时使用ON UPDATE SET DEFAULT时出错

时间:2017-03-22 18:01:05

标签: sql sql-server sql-server-2008-r2

我尝试使用ON UPDATE SET DEFAULT实现参照完整性的示例,但我收到错误。我试图搜索这个但我没有找到任何合适的例子。如果我在代码中的某处出错,请纠正我,或者给出一个帮助我实现和理解SET DEFAULT选项的示例。

code script

2 个答案:

答案 0 :(得分:0)

The default value needs to exist in the referenced table. It is still a foreign key, and as such needs to have referential integrity.

In your example, you need to have a tblGender.Id of 4 before updating tblGender.Id 6 to 7, so that tblPerson1 can successfully update to the default of 4.

For example:

create table Themes (
  ThemeID int primary key,
  ThemeName varchar(100),
);
insert into Themes (ThemeID, ThemeName) values (1,'Default'),(2,'Winter');

create table Users(
  UserID int primary key,
  UserName varchar(100),
  ThemeID int default 1 constraint Users_ThemeID_FK 
    /* if the default doesn't exist in the parent table
      , you will get an error on update --*/
    references Themes(ThemeID) 
        on update set default
        on delete set default 
);

insert into Users(UserID, UserName, ThemeID) values 
 (1,'JSmith',null),(2,'Ted',1),(3,'ARod',2)

-- update a theme that isn't the default
update themes set themeid = 3 where ThemeID = 2

-- And let's see what we've got:
select * from Users

-- Try to update the default and you will get an error
--update themes set themeid = 3 where ThemeID = 1

rextester demo: http://rextester.com/NGYBS91102

Reference:

Using set null and set default with Foreign Key Constraints - Jeff Smith

答案 1 :(得分:0)

I think this is because you don't have a matching ID of 4 (the default value) in the Gender table.

If you add this:

insert tblGender values (4, 'abc')

Then the update statement will run without error.