SQl Update on Multiple Records

时间:2019-04-08 13:57:53

标签: sql sql-server

StartDate       Departmentid    DateID
Jan 2010        3               500
Febuary 2011    8               501
March 2012      2               503
April 2013      1               504 

Update above where departmentID should have the values of DateID

above 2 columns are coming from different Tables:

StartDate is from [DatesAvaliable]
DepartmentID is from [Persons]
DateID is from [DatesAvaliable]

The query used to build it is the following:

select i.startdate,DepartmentID,i.id as DateID 
from persons p 
inner join substitutetable ppk on ppk.id = p.DepartmentID 
inner join DatesAvaliable i on i.id = ppk.DateAvaliableID 
where departmentID is not null 

This Table [substitutetable] kind of makes a connection between the table, otherwise the records I get are not possible

How can i write an update query to update the above records

Where i can replace the departmentID values with DateID?

2 个答案:

答案 0 :(得分:2)

If I'm following this correctly, which is confusing to begin with...

But if your select statement gets you what you need, then just turn your select statement into an update statement.

select i.startdate,DepartmentID,i.id as DateID 
from persons p 
inner join substitutetable ppk on ppk.id = p.DepartmentID 
inner join DatesAvaliable i on i.id = ppk.DateAvaliableID 
where departmentID is not null 

** UPDATE **

Update P
Set DepartmentID = i.id
from persons p 
    inner join substitutetable ppk on ppk.id = p.DepartmentID 
    inner join DatesAvaliable i on i.id = ppk.DateAvaliableID 
    where departmentID is not null 

答案 1 :(得分:0)

您还可以使用{{3}}(公用表表达式)

print(*row)