Microsoft SQL Server - restricting subqueries

2019-06-03 13:49发布

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. 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. Hence, finally, my question is:

What can you do to the Microsoft SQL Server settings or database structure that would create such a scenario?

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-06-03 14:38

What can you do to the Microsoft SQL Server settings or database structure that would create such a scenario?

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]

Subquery returned more than 1 value. 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

When only one row is affected everything works.

查看更多
登录 后发表回答