简体   繁体   English

Microsoft SQL Server-限制子查询

[英]Microsoft SQL Server - restricting subqueries

This is mostly a curiosity question. 这主要是一个好奇心问题。 I've just experienced a situation where on a test database I had the following query: 我刚遇到一种情况,在测试数据库上,我有以下查询:

update table 
set column1 = 1 
where column2 in (1,2)

But this kept executing with the error that subquery returned more than one value. 但这继续执行,并产生以下错误:子查询返回多个值。

Now I checked to make sure I did not have multiple identity keys or that the 'in' values were unique. 现在,我检查以确保没有多个身份密钥,或者“ in”值是唯一的。 so for all intents and purposes this should not have happened. 因此,就所有意图和目的而言,这都不应该发生。

Checking on the LIVE copy of the database, same query did not have an issue. 检查数据库的LIVE副本,相同查询没有问题。 Hence, finally, my question is: 因此,最后,我的问题是:

What can you do to the Microsoft SQL Server settings or database structure that would create such a scenario? 您会如何处理会造成这种情况的Microsoft SQL Server设置或数据库结构?

What can you do to the Microsoft SQL Server settings or database structure that would create such a scenario? 您会如何处理会造成这种情况的Microsoft SQL Server设置或数据库结构?

As mentioned in comments you probably have poorly written trigger. 如评论中所述,您可能没有编写好的触发器。 Sample scenario: 示例场景:

CREATE TABLE aud(column2 INT, comment NVARCHAR(150));
CREATE TABLE tab(column1 INT, column2 INT);

INSERT INTO aud(column2) VALUES (1),(2),(3);
INSERT INTO tab(column1, column2) VALUES (0,1),(-1, 2), (-2,3);
GO

CREATE TRIGGER trg_tab_i ON tab 
FOR UPDATE
AS
BEGIN
   UPDATE aud
   SET comment = 'Changed value ...'
   WHERE column2 = (SELECT column2 FROM inserted);
END
GO


UPDATE tab
SET column1 = 1 
WHERE column2 in (1,2);

Msg 512, Level 16, State 1, Procedure trg_tab_i, Line 5 [Batch Start Line 19] 消息512,级别16,状态1,过程trg_tab_i,第5行[批处理开始第19行]

Subquery returned more than 1 value. 子查询返回的值超过1。 This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. 当子查询遵循=,!=,<,<=,>,> =或将子查询用作表达式时,不允许这样做。

UPDATE tab
SET column1 = 1 
WHERE column2 in (1);
-- (1 row(s) affected)
-- (1 row(s) affected)

DBFiddle Demo DBFiddle演示

When only one row is affected everything works. 当只有一行受到影响时,一切正常。

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

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