简体   繁体   中英

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. 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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