简体   繁体   English

为什么此更新不会失败? 这是预期的行为吗?

[英]Why doesn't this Update fail? is this intended behavior?

I'm trying to understand why this update doesn't fail, and instead updates the table even though the sub-query contains an incorrect column name that doesn't exist in the table it is selecting from. 我试图理解为什么此更新不会失败,而是更新了表,即使子查询包含不正确的列名,该列名也不存在于从其选择的表中。 If you run the sub-query by itself it returns a syntax error. 如果您单独运行子查询,它将返回语法错误。 Shouldn't the update fail and give an error? 更新是否应该失败并给出错误? How is this being interpreted? 如何解释? a Co-worker suggested it may be interpreting this as a cross-apply, is that a possiblity? 一位同事建议说这可能是交叉应用,这是可能吗?

Create table MyTable(column1 nvarchar(max), column2 nvarchar(max) , exclude nvarchar(max))
Create table MyTable2(c1 varchar)

INSERT INTO MyTable (column1, column2, exclude)
VALUES
    ('Fred', 'Smith',0),
    ('John', 'Smith',0),
    ('Michael', 'Smith',0),
    ('Robert', 'Smith',0);

INSERT INTO MyTable2
  ( c1)
VALUES
  ('x' ), 
  ('y'), 
  ('w'),
  ('n')

  Update [MyTable]  set [exclude] = 1 where [column1] in (select [column1] from [MyTable2])

  drop table MyTable
  drop table MyTable2

In the Sub-query for the update, Column1 does not exist. 在更新的子查询中,Column1不存在。 Despite this, the update runs on every row in the table. 尽管如此,更新仍在表中的每一行上运行。 If you run the sub-query by itself, it returns a syntax error. 如果您单独运行子查询,它将返回语法错误。

The expected behavior is that the update would fail, and the transaction would be rolled back 预期的行为是更新将失败,并且事务将被回滚

Yes. 是。 Expected. 预期。 [column1] is in scope in the subquery because it exists in the outer query. [column1]在子查询的范围内,因为它存在于外部查询中。

Eg, for lots of queries like: 例如,对于许多查询,例如:

 Update [MyTable]  
 set [exclude] = 1 
 where exists (select * from [MyTable2] where c1 = [column1])

It's both legal and necessary to reference columns from the outer query in the subquery. 从子查询的外部查询中引用列既合法又必要。

As @IłyaBursov points out, this is one of the many reasons to always prefix your column references with table aliases. 正如@IłyaBursov指出的,这是始终为表引用加上前缀列别名的众多原因之一。

eg: 例如:

 Update [MyTable] t  
 set t.[exclude] = 1 
 where t.[column1] in (select t2.[column1] from [MyTable2] t2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM