2010-03-22 149 views
2

我有以下查询列出两个表的雇员。SQL更新查询选择查询

我需要将a.staffdiscountstartdate更新为'20100428'如何为此重写以下查询?

select 
    a.employeeid, 
    b.employeeid 
from 
    tblEmployees a 
     left join 
    tblCards b 
     on 
      a.employeeid=b.employeeid 
where 
    GroupStartDate < '20100301' 
and 
    StaffDiscountStartDate > '20100428' 
and 
    datediff(day,groupstartdate,staffdiscountstartdate)>1 
and 
    b.employeeid is null 

回答

2

应该只是能够做到:

UPDATE a 
SET a.staffdiscountstartdate = '20100428' 
from tblEmployees a 
    left join tblCards b on a.employeeid=b.employeeid 
where GroupStartDate < '20100301' 
and StaffDiscountStartDate > '20100428' 
and datediff(day,groupstartdate,staffdiscountstartdate)>1 
and b.employeeid is null 

MS SQL只。其他SQL版本不支持此语法。

2

两种方法。

一:

update tblEmployees 
set staffdiscountstartdate = '20100428' 
where employeeid in (
    -- original select query here, remove b.employeeid from the select results 
) 

二:

update a 
set a.staffdiscountstartdate = '20100428' 
from tblEmployees a 
    left join 
tblCards b 
    on 
     a.employeeid=b.employeeid 
where 
    GroupStartDate < '20100301' 
and 
    StaffDiscountStartDate > '20100428' 
and 
    datediff(day,groupstartdate,staffdiscountstartdate)>1 
and 
    b.employeeid is null 

要么将​​工作。

+0

+1第一部分也是我的解决方案(我现在将删除...该死的我的手指慢...) – amelvin 2010-03-22 16:30:05

1
update 
    tblEmployees 
set 
    staffdiscountstartdate = '20100428' 
where 
    employeeid in (
    select 
     a.employeeid 
    from 
     tblEmployees a 
      left join 
     tblCards b 
      on 
       a.employeeid=b.employeeid 
    where 
     GroupStartDate < '20100301' 
    and 
     StaffDiscountStartDate > '20100428' 
    and 
     datediff(day,groupstartdate,staffdiscountstartdate)>1 
    and 
     b.employeeid is null 
    ) 
+0

+1 - 我会删除我的重复的答案,这一个。 – amelvin 2010-03-22 16:27:55

0
Update a 
Set staffdiscountstartdate = '20100428' 
--select a.employeeid, b.employeeid 
from 
    tblEmployees a 
     left join 
    tblCards b 
     on 
      a.employeeid=b.employeeid 
where 
    GroupStartDate < '20100301' 
and 
    StaffDiscountStartDate > '20100428' 
and 
    datediff(day,groupstartdate,staffdiscountstartdate)>1 
and 
    b.employeeid is null 
and 
    a. staffdiscountstartdate <> '20100428'  

我增加了一个额外的where子句作为谁需要,如果它已经存在,正确地更新值。我还演示了如何通过在一行中注释语句的select和column list部分来将select用作更新的一部分。这可以帮助您在运行更新之前看到您拥有正确的记录,并且我认为可以更轻松地了解如何将选择的统计信息转换为更新。