views:

114

answers:

4

i have the following query to list the employees of two table.

i need to update the a.staffdiscountstartdate to '20100428' how to rewrite the following query for this?

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  A: 

Should be just able to do:

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 only. Other SQL versions don't support this syntax.

BradC
+2  A: 

Two methods.

One:

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

Two:

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

Either will work.

technophile
+1 Part one is also the same as my solution (which I'll now delete ... damn my slow fingers ...)
amelvin
+1  A: 
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
    )
Mario Menger
+1 - I'll delete my duplicate answer to this one.
amelvin
A: 
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'    

I added an additional where clause as who needs to update the value if it is already there correctly. I also showed how to use the select as part of the update by commenting out the select and column list part of the statement on one line. THis helps you see that you have the correct records before you run the update and I think it makes it easier to see how to convert a select statment to an update.

HLGEM