使用错误的列名执行查询时没有错误

问题描述 投票:0回答:1

尝试删除某些记录时,至少在SQL Server上遇到了奇怪的行为(我仍然需要检查其他SQL引擎)。>

我在SQL Server实例上测试了以下内容:

  • Microsoft SQL Server 2019(RTM)-15.0.2000.5(X64)2019年9月24日13:48:23版权所有(C)2019 Windows 10 Enterprise 2016 LTSB 10.0(内部版本14393:)的Microsoft Corporation Developer Edition(64位)
  • Microsoft SQL Server 2016(SP1)(KB3182545)-13.0.4001.0(X64)2016年10月28日18:17:30版权所有(c)Windows Server 2012 R2 Standard 6.3(Build 9600)上的Microsoft Corporation标准版(64位) :)(管理程序)
  • 这里是一个SQL代码段。这是我正在尝试做的简化版本,可以肯定地讨论为什么要用这种方式进行查询,但是我的观点是不同的-为什么会发生。

    drop table if exists #A
    drop table if exists #B

    create table #B (id char, foo char) -- I use different types for id columns just for the sake of readability
    create table #A (id int, b_id char) -- b_id is a link to #A, _not_ specified as FK

    insert into #B values('x', 'l')
    insert into #B values('y', 'm')

    insert into #A values(0, 'x')
    insert into #A values(1, 'z')
    insert into #A values(2, 'z')
    insert into #A values(3, 'y')
    insert into #A values(4, 'y')
    insert into #A values(5, 'y')

    -- there are 2 parent records in #B and 3 child records for each of them in #A
    select * from #A -- just to check, all good the data is there, all as expected, no problem

    -- now the fun part

    --(X) the following query, rightfully gives an error, as column b_id does not exist in #B
    -- select b_id from #B where foo='l'

    --(Y) the following query gives empty result, whereas I would expect an error:
    select * from #A where b_id in (select b_id from #B where foo='l')
    -- I can imagine that this has something to do with the fact that b_id exists in table #A in outer query

    --(Z) the following query deletes(!) all data in table #A:
    delete from #A where b_id in (select b_id from #B where foo='l')
    select * from #A
    -- once again, I can imagine that there is no error message "Invalid column name 'b_id'." because b_id exists in table #A in outer query

所以这是我的问题:

  1. 为什么在查询(Y)和(Z)中没有关于无效列的错误消息?我会对详细信息感兴趣
  2. 取决于答案(1),知道为什么查询(Y)提供空结果会很有趣。显然,如果内部选择为空,那么外部应该为空,但详细信息中会隐藏魔鬼
  3. 为什么查询(Z)删除表#A中的所有记录?我希望受影响的记录(在(Y)的情况下返回并在(Z)的情况下删除)应该是相同的

我在尝试删除某些记录时,至少在SQL Server上遇到了奇怪的行为(我仍然需要检查其他SQL引擎)。我在SQL Server实例上测试了以下内容:Microsoft SQL ...

sql sql-server database select sql-delete
1个回答
0
投票

查询

© www.soinside.com 2019 - 2024. All rights reserved.