使用子查询插入多行

时间:2012-12-11 23:34:35

标签: sql sql-server database

这是查询:

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

如果我尝试执行查询,这是我得到的错误。

  

Msg 512,Level 16,State 1,Line 1 Subquery返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。声明已经终止。

如果有人告诉我任何替代方法,我是新来的SQL。

5 个答案:

答案 0 :(得分:21)

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

答案 1 :(得分:3)

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

语法是否正确

答案 2 :(得分:2)

问题是这个子查询:

select Qualification from student where Qualification like 'A%'

返回几行。这就是您收到错误消息512

的原因

无需使用它。

这就足够了:

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

答案 3 :(得分:2)

您需要考虑如何构建查询 - 考虑一下如果你运行它会得到什么:

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

你得到的确切错误将是我的猜测 - 你有一个许多资格的列表,试图与一个字符串匹配 - 'A-level'。

另一方面,这样可以正常使用

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

我想到的是INSERTUPDATE语句的技巧是编写一个SELECT语句,它可以为您提供所需内容,然后将其包装起来,如

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

答案 4 :(得分:0)

declare @count int
declare @index int = 1
declare @currentQualificationId int = null

set @count = (select distinct count(QualificationId) from Qualification  from  where 
Qualification like 'A%')

set @currentQualificationId = (SELECT QualificationId from (select QualificationId , 
ROW_NUMBER() OVER (ORDER BY QualificationId) AS RowNumber from Qualification where 
Qualification like 'A%') as Qualification
where Qualification.RowNumber = @index) 


while (@index <= @count)
 begin

    INSERT INTO qualification_lookup (variation, correct_qualification) 
     values((select Qualification where QualificationId = 
     @currentQualificationId),'A-Level')

    set @index = @index + 1

     set @currentQualificationId = (SELECT QualificationId from (select 
     QualificationId , ROW_NUMBER() OVER (ORDER BY QualificationId) AS RowNumber from 
     Qualification where Qualification like 'A%') as Qualification
     where Qualification.RowNumber = @index) 
END