2010-03-22 124 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用作更新的一部分。這可以幫助您在運行更新之前看到您擁有正確的記錄,並且我認爲可以更輕鬆地瞭解如何將選擇的統計信息轉換爲更新。