Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert multiple rows using subquery

This is the query:

INSERT INTO qualification_lookup (variation, correct_qualification)
SELECT (SELECT Qualification FROM student WHERE Qualification like 'A%') ,'A-Level'

This is the error I get if I try to execute the query.

Msg 512, Level 16, State 1, Line 1 Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. The statement has been terminated.

I am new to SQL so kindly if someone tells me any alternative to do that.

like image 668
Umar Iqbal Avatar asked Dec 11 '12 23:12

Umar Iqbal


4 Answers

INSERT INTO qualification_lookup (variation, correct_qualification) 
select Qualification,'A-Level' from student   where Qualification like 'A%' 
like image 110
Kaf Avatar answered Oct 22 '22 13:10

Kaf


You need to think through how you build your query - consider what you would get if you just ran this:

 SELECT (select Qualification from student where Qualification like 'A%') ,'A-Level'

the exact error you are getting would be my guess - you have a list of many Qualifications trying to be matched with a single string - 'A-level'.

On the other hand, this will work fine

 select Qualification, 'A-Level' from student where Qualification like 'A%'

The trick with INSERT and UPDATE statements, to my mind is to write a SELECT statement that gets you what you need and then wrap that up like

INSERT INTO qualification_lookup (variation, correct_qualification) select Qualification, 'A-Level' from student where Qualification like 'A%'
like image 43
Dale M Avatar answered Oct 22 '22 13:10

Dale M


    INSERT INTO qualification_lookup (variation, correct_qualification) 
select Qualification, 'A-Level' from student where Qualification like 'A%'

Is the correct syntax

like image 3
jenson-button-event Avatar answered Oct 22 '22 12:10

jenson-button-event


The problem is this subquery:

select Qualification from student where Qualification like 'A%'

returns several rows. That's why you get error message 512

No need to use that.

This would be enough:

INSERT INTO qualification_lookup (variation, correct_qualification) 
select Qualification, 'A-Level' as correct_qualification
from student where Qualification like 'A%'
like image 2
Nathan Avatar answered Oct 22 '22 11:10

Nathan