关键字'然后'附近的语法不正确在if语句中

时间:2014-12-30 04:52:27

标签: sql sql-server sql-server-2008

我在运行此查询时出现问题,显示“关键字'附近的语法不正确,然后'”,CorrectAnswer和AnswerID的数据类型为varchar(10)。

   select  T.[AssociateID],  
           T.[QuestionID],  
           T.[Result]  
   from
        AssociateAssessmentTransaction T  
        left join   
        AssessmentQuestions A  
        on  T.[QuestionID]=T.[QuestionID]  
        group by T.[AssociateID],
                 T.[QuestionID],
                 T.[Result]
        if(A.[CorrectAnswer] = T.[AnswerID]) 
          then 
          T.[Result] = 1;
        else  
          T.[Result] = 0;
        end if    

3 个答案:

答案 0 :(得分:6)

您不能在声明

中使用if then这样的内容

你应该这样使用

   select  T.[AssociateID],  
           T.[QuestionID],  
           case when A.[CorrectAnswer] = T.[AnswerID] 
           then 1 else 0 end as Result
   from
        AssociateAssessmentTransaction T  
        left join   
        AssessmentQuestions A  
        on  T.[QuestionID]=T.[QuestionID]  
        group by T.[AssociateID],
                 T.[QuestionID],
                 T.[Result]

答案 1 :(得分:0)

如果select select中没有其他内容,则可以使用case语句

select  T.[AssociateID],  
           T.[QuestionID],  
           T.[Result]  
   from
        AssociateAssessmentTransaction T  
        left join   
        AssessmentQuestions A  
        on  T.[QuestionID]=T.[QuestionID]  
        and T.[Result] =
            case when (A.[CorrectAnswer] = T.[AnswerID]) 
               then 1;
            else  0;
          end

        group by T.[AssociateID],
                 T.[QuestionID],
                 T.[Result]

答案 2 :(得分:-1)

我认为您正在搜索案例

    select  T.[AssociateID],  
               T.[QuestionID],  
               T.[Result]  ,
  case when A.[CorrectAnswer] = T.[AnswerID]
              then 
              T.[Result] = 1;
            else  
              T.[Result] = 0;
            end as Result
       from
            AssociateAssessmentTransaction T  
            left join   
            AssessmentQuestions A  
            on  T.[QuestionID]=T.[QuestionID]  
            group by T.[AssociateID],
                     T.[QuestionID],
                     T.[Result]