MSSQL子查询返回值

时间:2015-05-18 16:07:39

标签: sql-server

如果以下查询返回的值小于45,我需要一个返回'True'的查询。

select sum(assignmentPoints) as Points from Assignment a join Studies s
on a.courseCode = s.courseCode and a.assignmentName = s.assignmentName and a.sectionName = s.sectionName and pnr = '851326'
where assignmentPoints > 45

如果查询返回的值大于45,我还希望查询返回'False',如果该查询返回'null',则换句话说。

有人可以帮帮我吗?

/////修改

您是否知道是否可以将该查询转换为函数?就像函数会根据查询返回False或True一样。

/////修改

M.Ali和huMpty duMpty提出了解决方案!

2 个答案:

答案 0 :(得分:3)

select CASE 
           WHEN  sum(assignmentPoints) > 45 
             THEN 'TRUE'
            ELSE 'FALSE' 
       END as Points 
from Assignment a 
join Studies s  on a.courseCode     = s.courseCode 
               and a.assignmentName = s.assignmentName 
               and a.sectionName    = s.sectionName 
               and pnr              = '851326'

答案 1 :(得分:1)

您可以创建一个功能。 我使用了与M.ALi相同的代码

CREATE FUNCTION fn_FunctionName
(
    -- Add the parameters for the function here
    @PNR VARCHAR(50)
)
RETURNS BIT
AS
BEGIN
    -- Declare the return variable here
    DECLARE @Result BIT =0 

    select @Result = CASE 
               WHEN  sum(assignmentPoints) > 45 
                 THEN 1
                ELSE 0
           END
    from Assignment a 
    join Studies s  on a.courseCode     = s.courseCode 
                   and a.assignmentName = s.assignmentName 
                   and a.sectionName    = s.sectionName 
                   and pnr              = @PNR


    -- Return the result of the function
    RETURN @Result

END
GO