如何从选择另一个表更新?

时间:2012-11-11 16:49:08

标签: sql-server select subquery sql-update insert-update

我需要在2个表之间选择更新字段'ErrCode'。我尝试查询它更新所有记录。

表格LeaveEmp

EmpRun Date                      Start                    Stop
00003  2012-10-02 00:00:00.000   2012-10-02 13:00:00.000  2012-10-02 17:00:00.000
00004  2012-10-02 00:00:00.000   NULL                     NULL

表格修改时间

EmpNo  cDate                     cIn                      cOut                      ErrCode
00001  2012-10-02 00:00:00.000   NULL                     NULL                      NULL
00002  2012-10-02 00:00:00.000   2012-10-02 07:35:00.000  2012-10-02 20:12:00.000   NULL
00003  2012-10-02 00:00:00.000   2012-10-02 13:00:00.000  2012-10-02 17:00:00.000   NULL 
00004  2012-10-02 00:00:00.000   NULL                     NULL                      NULL
00005  2012-10-02 00:00:00.000   2012-10-02 07:13:00.000  2012-10-02 19:24:00.000   NULL
00006  2012-10-02 00:00:00.000   2012-10-02 07:55:00.000  2012-10-02 20:58:00.000   NULL
*****00003,00004 from Table LeaveEmp.step one i insert Table LeaveEmp to Table modifyTime**

UPDATE modifyTime
SET ErrCode = '3'
WHERE EXISTS (SELECT coalesce(l.Start,'2012-10-02')
FROM LeaveEmp l
WHERE l.Start = '2012-10-02' and modifyTime.cDate = '2012-10-02')

此获取输出:

EmpNo  cDate                     cIn                      cOut                      ErrCode
00001  2012-10-02 00:00:00.000   NULL                     NULL                      3
00002  2012-10-02 00:00:00.000   2012-10-02 07:35:00.000  2012-10-02 20:12:00.000   3
00003  2012-10-02 00:00:00.000   2012-10-02 13:00:00.000  2012-10-02 17:00:00.000   3 
00004  2012-10-02 00:00:00.000   NULL                     NULL                      3
00005  2012-10-02 00:00:00.000   2012-10-02 07:13:00.000  2012-10-02 19:24:00.000   3
00006  2012-10-02 00:00:00.000   2012-10-02 07:55:00.000  2012-10-02 20:58:00.000   3

但我需要输出:

EmpNo  cDate                     cIn                      cOut                      ErrCode
00001  2012-10-02 00:00:00.000   NULL                     NULL                      NULL
00002  2012-10-02 00:00:00.000   2012-10-02 07:35:00.000  2012-10-02 20:12:00.000   NULL
00003  2012-10-02 00:00:00.000   2012-10-02 13:00:00.000  2012-10-02 17:00:00.000   3 
00004  2012-10-02 00:00:00.000   NULL                     NULL                      3
00005  2012-10-02 00:00:00.000   2012-10-02 07:13:00.000  2012-10-02 19:24:00.000   NULL
00006  2012-10-02 00:00:00.000   2012-10-02 07:55:00.000  2012-10-02 20:58:00.000   NULL

我只需要从Table LeaveEmp更新。

谢谢你的时间。 :)

1 个答案:

答案 0 :(得分:1)

你缺少modifyTime和LeaveEmp之间的链接......试试这个

UPDATE modifyTime
SET ErrCode = '3'
FROM modifyTime m
INNER JOIN LeaveEmp l
  ON m.EmpNo = l.EmpRun
WHERE l.Start = '2012-10-02' and modifyTime.cDate = '2012-10-02'