-4

I have two tables of same structure and want to insert rows from tableA into tableB.

The following example works fine:

INSERT INTO tableA (uniqueColA, colB, colC)
    SELECT uniqueColA, colB, colC FROM tableB 
    WHERE uniqueColA = 1
 

However, if the SELECT returns more than one row, like

INSERT INTO tableA (uniqueColA, colB, colC)
    SELECT uniqueColA, colB, colC FROM tableB 
    WHERE uniqueColA IN (1,2)

SQL Server returns the error

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

Why that, and how can I solve this?

EDIT: The parentheses around the columns of the SELECT were a typo. Wether there are parentheses around the entire SELECT...WHERE... does not matter, it throws the same error.

4
  • 3
    You are misusing parenthesis. (SELECT (uniqueColA, colB, colC) FROM ... <> SELECT (uniqueColA, colB, colC) .FROM... <> SELECT uniqueColA, colB, colC FROM.... The only places you should have parenthesis are in your INSERT and IN clauses. Commented Mar 21 at 10:37
  • 3
    Do you perhaps have a faulty trigger in your table? Add full query and the full error message Commented Mar 21 at 11:54
  • 1
    I see you fixed the code in your question. As @siggemannen suggested, the error is likely due to a trigger on tableA which is not properly written to handle multiple rows. Remember that triggers fire once per statement rather than per row so the virtual inserted table in the trigger may contain multiple rows. Commented Mar 21 at 14:44
  • You need to provide minimal reproducible example here. Most likely, as mentioned, there's a poorly written trigger, so you need to provide a copy of the trigger's definition. Commented Apr 11 at 9:12

1 Answer 1

1

No need to wrap select statement in parentheses.

You need to query like this and it will work:

INSERT INTO tableA (uniqueColA, colB, colC)
SELECT uniqueColA, colB, colC 
FROM tableB 
WHERE uniqueColA IN (1,2)
Sign up to request clarification or add additional context in comments.

2 Comments

Actually, it does not. I had some extra parentheses in my question, my original query looks like yours - yet, SQL Server says the SELECT returns more than one result...
Put your real query in the question, this should work, so i'm guessing your actual query isn't exactly like that

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.