2

请注意,在下面的查询中,括号内的前两个查询,我添加了两个重复的查询,我确信这不是一个好习惯。我需要在需要该值的任何时候重复此查询。

SQL Server 引发了一个关于不要在 SELECT 关键字内写入 DECLARE 的异常。我能做什么或者我缺少什么来重构它?

SELECT A.StudentId,
(
    CASE WHEN (SELECT B.OverwrittenScore
        FROM dbo.OverwrittenScores AS B
        WHERE B.StudentId = A.StudentId 
        AND B.AssignmentId = @assignmentId
        ) IS NOT NULL
            THEN (
                SELECT B.OverwrittenScore
                FROM dbo.OverwrittenScores AS B
                WHERE B.StudentId = A.StudentId 
                AND B.AssignmentId = @assignmentId)
            ELSE (-- ANOTHER QUERY, BY THE MOMENT: SELECT 0 ) 
    END
) AS FinalScore
FROM dbo.Students AS A
4

2 回答 2

6

我的建议是考虑使用JOIN

SELECT A.StudentId,
    case 
        when B.OverwrittenScore is not null
        then B.OverwrittenScore
        else 0 
    end AS FinalScore
FROM dbo.Students AS A
LEFT JOIN dbo.OverwrittenScores B
    ON B.StudentId = A.StudentId 
    AND B.AssignmentId = @assignmentId

如果您想在 else 中使用另一个选择,那么您可以根据需要添加更多连接:

SELECT A.StudentId,
    case 
        when B.OverwrittenScore is not null
        then B.OverwrittenScore
        else c.whatever
    end AS FinalScore
FROM dbo.Students AS A
LEFT JOIN dbo.OverwrittenScores B
    ON B.StudentId = A.StudentId 
    AND B.AssignmentId = @assignmentId
LEFT JOIN anothertable c
   ON a.col = c.col

甚至你可以COALESCE用来替换空值:

SELECT A.StudentId,
    coalesce(B.OverwrittenScore, 0) as FinalScore 
FROM dbo.Students AS A
LEFT JOIN dbo.OverwrittenScores B
    ON B.StudentId = A.StudentId 
    AND B.AssignmentId = @assignmentId
于 2013-05-15T20:37:11.190 回答
0

不知道错误DECLARE来自哪里,但你可以改变你所做的显示

SELECT 
    A.StudentId,
    COALESCE(B.OverwrittenScore, 0) AS FinalScore
FROM dbo.Students AS A
LEFT JOIN dbo.OverwrittenScores AS B
    ON A.StudentId = B.StudentId AND B.AssignmentId = @assignmentId
于 2013-05-15T20:39:18.670 回答