Microsoft SQL Server - restricting subqueries

自作多情 提交于 2019-12-08 06:49:46

问题


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:


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.



来源:https://stackoverflow.com/questions/45575610/microsoft-sql-server-restricting-subqueries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!