Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a case statement in scalar valued function in SQL?

I want to get one value from a function using a case statement. I tried the following but it does not work:

CREATE FUNCTION [FATMS].[fnReturnByPeriod]
(

    @Period INT

)
RETURNS int
AS
BEGIN

    SELECT CASE @Period 
             when 1 then 1
             when @Period >1 and @Period <=7 then 1
             when @Period >7 and @Period <=30 then 1
             when @Period >30 and @Period<=90 then 1
             when @Period >90 and @Period <=180 then 1
             when @Period >180 and @Period <=360 then 1
             else 0
           END

    RETURN @Period
END
like image 728
HAJJAJ Avatar asked Feb 21 '11 19:02

HAJJAJ


People also ask

Can we use case statement in SQL function?

SQL queries use the ORDER BY clause for data sorting in either ascending or descending order. You can use the CASE statements in conjunction with the ORDER BY clause.

How do you handle a case statement in SQL?

SQL Server CASE statement syntax The CASE statement has to be included inside the SELECT Statement. It starts with the CASE keyword followed by the WHEN keyword and then the CONDITION. The condition can be any valid SQL Server expression which returns a boolean value.

Can we use select statement in scalar function?

"Select statements included within a function cannot return data to a client."


2 Answers

There are two types of CASE expression: simple and searched. You must choose one or the other - you can't use a mixture both types in one expression.

Try this:

SELECT CASE
    WHEN @Period = 1 THEN 1
    WHEN @Period > 1 AND @Period <= 7 THEN 2
    WHEN @Period > 7 AND @Period <= 30 then 3
    -- etc...
    ELSE 0
END

Also, you need to assign the result to something as others have already pointed out.

like image 173
Mark Byers Avatar answered Sep 23 '22 22:09

Mark Byers


When you use RETURN @Period, you must assign a value to @Period. The following example shows how to structure your code so that there is no need to declare a local variable.

CREATE FUNCTION [FATMS].[fnReturnByPeriod]
(
    @Period INT
)
RETURNS INT
AS
BEGIN
    RETURN
        CASE 
            WHEN @Period = 1 THEN 1
            WHEN @Period > 1 AND @Period <=7 THEN 1
            WHEN @Period > 7 AND @Period <=30 THEN 1
            WHEN @Period > 30 AND @Period<=90 THEN 1
            WHEN @Period > 90 AND @Period <=180 THEN 1
            WHEN @Period > 180 AND @Period <=360 THEN 1
            ELSE 0
        END 
END
like image 26
bernd_k Avatar answered Sep 24 '22 22:09

bernd_k