SQL Server删除具有无效查询的记录

时间:2016-10-19 14:04:01

标签: sql-server

我最近在SQL Server中运行了一个查询,该语句中包含无效的SQL,无意中删除了表中的所有记录。接下来是查询(以及它的近似值)。我真的不明白这是怎么发生的,因为查询应该给我一个错误。 'select test from testtable2'是一个无效的陈述。我希望有人可以解释这是一个有效的查询,以及它为什么运行。结果是testtable1中的所有行都被删除。

CREATE TABLE [dbo].[TestTable1](
    [ID] [int] NOT NULL,
    [blah] [int] NULL,
 CONSTRAINT [PK_TestTable1] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
CREATE TABLE [dbo].[TestTable2](
    [ID] [int] NOT NULL,
 CONSTRAINT [PK_TestTable2] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
insert into testtable1 (id, blah) values (1, 1)
insert into testtable1 (id, blah) values (2, 2)

insert into testtable2 (id) values (1)
insert into testtable2 (id) values (2)

delete from testtable1 where id in (select blah from testtable2)

2 个答案:

答案 0 :(得分:1)

它只会删除它们,因为你的数据中的id和blah匹配,你已经有效地说了

delete from testtable1 where id in (blah, blah)

id恰好匹配blah,对于testtable2中的每一行,你从table1中选择了blah

  • 将DELETE更改为SELECT,看看如果id不等于blah
  • 会发生什么

答案 1 :(得分:0)

public class ServiceFromTheOtherJar {

  private String someFieldWeWantToFillFromPropertyFile;

  public void setSomeFieldWeWantToFillFromPropertyFile(String someFieldWeWantToFillFromPropertyFile) {
    this.someFieldWeWantToFillFromPropertyFile = someFieldWeWantToFillFromPropertyFile;
  }

  public void call() {
    //we would like to use the filled someFieldWeWantToFillFromPropertyFile here
    ...

虽然delete from testtable1 where id in (select blah from testtable2) 中不存在blah,但没有错误,因为它确实存在于外部查询(testtable2)中,所以声明没问题。

testtable1

会失败,因为delete from testtable1 where id in (select xblah from testtable2) 中也不存在,但是对于限定名称也是如此:

xblah