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
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.
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.
"Select statements included within a function cannot return data to a client."
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With