选择查询的SQL Update查询

时间:2010-03-22 16:20:08

标签: sql sql-server tsql

我有以下查询列出两个表的员工。

我需要将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

4 个答案:

答案 0 :(得分: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版本不支持此语法。

答案 1 :(得分: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

要么工作。

答案 2 :(得分: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
    )

答案 3 :(得分: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作为更新的一部分。这有助于您在运行更新之前看到正确的记录,我认为这样可以更轻松地查看如何将选择的状态转换为更新。