11

这是查询:

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

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

消息 512,级别 16,状态 1,第 1 行子查询返回超过 1 个值。当子查询跟随 =、!=、<、<=、>、>= 或子查询用作表达式时,这是不允许的。该语句已终止。

如果有人告诉我任何替代方法,我对 SQL 很陌生。

4

5 回答 5

24
INSERT INTO qualification_lookup (variation, correct_qualification) 
select Qualification,'A-Level' from student   where Qualification like 'A%' 
于 2012-12-11T23:37:48.137 回答
3

您需要考虑如何构建查询 - 考虑如果您只运行以下命令会得到什么:

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

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

另一方面,这将正常工作

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

INSERT在我看来, and语句的诀窍UPDATE是写一个SELECT语句,让你得到你需要的东西,然后把它包装起来

INSERT INTO qualification_lookup (variation, correct_qualification) select Qualification, 'A-Level' from student where Qualification like 'A%'
于 2012-12-11T23:42:44.603 回答
3
    INSERT INTO qualification_lookup (variation, correct_qualification) 
select Qualification, 'A-Level' from student where Qualification like 'A%'

是正确的语法

于 2012-12-11T23:37:37.077 回答
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%'
于 2012-12-11T23:41:59.167 回答
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
于 2018-08-06T14:36:27.073 回答