绕过SubQuery返回超过1个值的错误

时间:2015-06-09 21:04:14

标签: sql-server-2008

我正在尝试阅读在课堂上花费的时间,并且我的查询不断产生错误

  

子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。

我怎样才能解决这个问题?

Declare 
@timespentinclass decimal(18,2),
@courseID varchar(50),
@course varchar(50),
@studentID varchar(50),
@count int

Set @courseID = '2'

Create Table Course (course varchar(MAX),coursename varchar(MAX),timespentinclass int,studentID varchar(50),dun int)
Create Table coursesOffered(course varchar(Max),courseIDUsed varchar(50),courseID varchar(50))  
Create Table timespentinclass(coursetaken varchar(Max),studentID varchar(50),studentinfo varchar(MAX),daysattended decimal(18,2))

SET @count = (SELECT COUNT(*) FROM courses)

while @count > 0

BEGIN

SET @course = (SELECT TOP 1 course FROM courses WHERE dun IS NULL)
SET @courseID = (SELECT TOP 1 courseIDUsed FROM coursesOffered WHERE courseID = @course)

BEGIN

    set @timespentinclass = (select (convert(decimal(18,2),SUM(daysattended)),2)
    from timespentinclass t
    RIGHT JOIN courses al
    ON t.studentID = al.studentID
    where course = @courseID
    and t.studentID = al.studentID) 

END

update course set
timespentinclass = @timespentinclass    
where course = @course
and dun is null 

set @count = @count - 1     

UPDATE courses
SET dun = 1
WHERE studentID = @studentID

END

编辑1 将Top 1添加到此语句将不再产生错误,但它为该类的所有学生提供了timepentinclass的相同值?

set @timespentinclass = (select Top 1(convert(decimal(18,2),SUM  (daysattended)),2)
from timespentinclass t
RIGHT JOIN courses al
ON t.studentID = al.studentID
where course = @courseID
and t.studentID = al.studentID)

2 个答案:

答案 0 :(得分:2)

我想我发现了这个问题。看看这个:

(select (convert(decimal(18,2),SUM(daysattended)),    2)

您在这里选择转换值和2.您放错了方括号。我认为应该是:

set @timespentinclass = (select convert(decimal(18,2), SUM(daysattended), 2)
from timespentinclass t
RIGHT JOIN courses al
ON t.studentID = al.studentID
where course = @courseID
and t.studentID = al.studentID)

但我总是喜欢以下语法:

select @timespentinclass = convert(decimal(18,2), SUM(daysattended), 2)
from timespentinclass t
RIGHT JOIN courses al ON t.studentID = al.studentID
where course = @courseID

答案 1 :(得分:1)

我认为下面的代码块正在创建问题

set @timespentinclass = (select (convert(decimal(18,2),SUM(daysattended)),2)
from timespentinclass t
RIGHT JOIN courses al

您可以使用TOP关键字获取单个数据记录(或)将@timespentinclass声明为表变量以解决此问题。