从另一个连接列更新列,

时间:2013-04-09 06:28:47

标签: sql-server join sql-update

首先它应该对DB'es来说很容易,但它真的让我痛苦,我不知道为什么,

我有两个表,[Table1]名为Applicationforms,[Table2]名为WFInstance 我需要使用表2中的startedDate值更新Table1中的FormSubmitDate FormSubmitDate为null。 我写了以下查询

UPDATE    ApplicationForm
SET              FormSubmitDate = wfi.StartDate
FROM         ApplicationForm app ,
                      WorkFlowInstances wfi

WHERE     app.FormSubmitDate is null and wfi.applicationID = app.ID 

当我运行查询时,SQL会将查询重新生成到这个查询,

UPDATE    ApplicationForm
SET              FormSubmitDate = wfi.StartDate
FROM         ApplicationForm AS app INNER JOIN
                      WorkFlowInstances AS wfi ON app.ID = wfi.ApplicationID CROSS JOIN
                      ApplicationForm
WHERE     (app.FormSubmitDate IS NULL)

我尝试使用join,

写另一个语句
UPDATE ApplicationForm
SET FormSubmitDate = wfi.StartDate
FROM ApplicationForm 
JOIN WorkFlowInstances wfi ON ApplicationForm.ID = wfi.ApplicationID 
WHERE  FormSubmitDate is null

并且SQL生成相同的新语法,

现在当我运行代码时,[所有记录] formSubmitDate字段填充第二个表startDate的第一个值。即使我有一个记录在table1中包含空值

我在这里缺少什么!?

1 个答案:

答案 0 :(得分:3)

我认为这可以满足您的需求。试一试,告诉我们。

UPDATE tabl3
SET formsubmitdate=(SELECT startdate
  FROM table4
  WHERE table4.id=tabl3.id AND tabl3.formsubmitdate is null);

编写相同内容的另一种方法是

UPDATE tabl3
SET formsubmitdate= startdate
FROM table4 where tabl3.id = table4.id and formsubmitdate is null