如何更新两个连接表?

时间:2012-10-17 07:07:21

标签: sql sql-server stored-procedures

我打算在SqlServer中编写一个可以更新连接表的程序,在我的情况下我有两个表(HowzeEducation& HowzeDegree)所以我写了下面的查询,但是它有错误并且无法正常工作。这是我的代码:

declare 
@HowzeEducationId int,
@DegreeId int,
@FieldName nvarchar(50),
@FinishLevelDate date,
@Average decimal(4,2),
@SchoolName nvarchar(50),
@StudyCityDescribtion nvarchar(100),
@ThesisTitle nvarchar(200),
@Describtion nvarchar(600)


update (
  select he.FieldName,
     he.Average,
     he.Describtion,
     he.FinishLevelDate,
     he.SchoolName,
     he.StudyCityDescribtion,
     he.ThesisTitle,
     hd.DegreeId
from HowzeEducation he inner join HowzeDegree hd on 
     he.HowzeEducationId=hd.HowzeEducationId
   )
 set he.FieldName=@FieldName ,
he.Average=@Average,
he.Describtion=@Describtion,
he.FinishLevelDate=@FinishLevelDate,
he.SchoolName=@SchoolName,
he.StudyCityDescribtion=@StudyCityDescribtion,
he.ThesisTitle=@ThesisTitle,
hd.DegreeId=@DegreeId

where he.HowzeEducationId=@HowzeEducationId

如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

您无法使用一个更新语句更新两个表,您必须使用以下两个更新:

declare 
@HowzeEducationId int,
@DegreeId int,
@FieldName nvarchar(50),
@FinishLevelDate date,
@Average decimal(4,2),
@SchoolName nvarchar(50),
@StudyCityDescribtion nvarchar(100),
@ThesisTitle nvarchar(200),
@Describtion nvarchar(600)


update HowzeEducation 
set Average=@Average,
    Describtion=@Describtion,
    FinishLevelDate=@FinishLevelDate,
    SchoolName=@SchoolName,
    StudyCityDescribtion=@StudyCityDescribtion,
    ThesisTitle=@ThesisTitle,
    FieldName=@FieldName
where HowzeEducationId=@HowzeEducationId

update HowzeDegree
set   DegreeId=@DegreeId
where HowzeEducationId=@HowzeEducationId

答案 1 :(得分:0)

您可以通过视图修改多个表,尝试类似:

create view HowzeView as
select he.FieldName,
     he.Average,
     he.Describtion,
     he.FinishLevelDate,
     he.SchoolName,
     he.StudyCityDescribtion,
     he.ThesisTitle,
     hd.DegreeId
from HowzeEducation he inner join HowzeDegree hd on 
     he.HowzeEducationId=hd.HowzeEducationId

update HowzeView
set FieldName=@FieldName,
Average=@Average,
Describtion=@Describtion,
FinishLevelDate=@FinishLevelDate,
SchoolName=@SchoolName,
StudyCityDescribtion=@StudyCityDescribtion,
ThesisTitle=@ThesisTitle,
DegreeId=@DegreeId