出于偶然,我注意到以下查询实际上是有效的:
UPDATE bikes
SET price = NULL
FROM inserted
WHERE inserted.owner_id = 123456
这是触发器的一部分,其中有人忘记将原始表连接到inserted
表。结果是,当执行触发器时,所有价格都设置为 NULL
。
正确的SQL语句是这样的:
UPDATE bikes
SET price = NULL
FROM inserted
INNER JOIN bikes ON bikes.id=inserted.id
WHERE inserted.owner_id = 123456
第一个声明如何/为什么有效?
最佳答案
为什么它无效? SQL Server 不知道您要做什么。它认为您想要更新另一个表上存在某些条件的所有字段。 请参阅下面的最新更新。
设置
declare @table table
(
id int,
name varchar(10)
)
declare @itable table
(
id int,
name varchar(10)
)
insert into @table (id, name)
select 1,'abc' union
select 2,'def' union
select 3,'ghi' union
select 4,'jkl' union
select 5,'mno' union
select 6,'pqr'
insert into @itable (id, name)
select 1,'abc' union
select 2,'def' union
select 3,'ghi' union
select 4,'jkl' union
select 5,'mno' union
select 6,'pqr'
@table 上的所有名称都将更改为 zzz
update @table
set name = 'zzz'
from @itable i
where i.id = 1
select * from @itable
select * from @table
@table 上 id = 1 的所有名称均变为 yyy
update @table
set name = 'yyy'
from @itable i
inner join @table t on i.id = t.id
where i.id = 1
select * from @itable
select * from @table
这不会更新任何内容
update @table
set name = 'aaa'
from @itable i
where i.id = 133
select * from @itable
select * from @table
关于from 子句中具有不同表的 SQL 更新语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38586365/