选择查询的SQL更新查询
我有下面的查询来列出两个表的雇员 我需要将a.staffdiscountstartdate更新为“20100428”,如何为此重写以下查询选择查询的SQL更新查询,sql,sql-server,tsql,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 &
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
应该能够做到:
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版本不支持此语法。有两种方法
一:
二:
两者都可以
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
)
我添加了一个额外的where子句,作为who需要更新该值(如果该值已经正确存在的话)。我还通过在一行上注释语句的select和column list部分,演示了如何将select用作更新的一部分。这有助于您在运行更新之前查看是否有正确的记录,我认为这样可以更轻松地查看如何将选择状态转换为更新。+1第一部分与我现在删除的解决方案相同。。。该死的我的慢手指。。。
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
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
)
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'