0

I need to create a scalar-valued user defined function in SQL Server. I need to have with clause to store some intermediary tables which will produce the final return result. I also need IF .. ELSE because depending on the input parameter the query to the resutl is different. However, I can't write the code without error combinaing these two elements together. My function would be like this:

             CREATE FUNCTION [dbo].[getMyValue](
               @inputType int      
               )
            RETURNS float
        AS
        BEGIN       

        DECLARE @result float
        ;

         WITH tempTable AS
            (
                SELECT * from TableA          
            )
              ;

           IF inputType = 1
           set @result = select sum(t.result1) from tempTable
           else 
           selecset @result = select sum(t.result2) from tempTable   
           return @result
        END
        GO

But now it complains incorrect syntax near 'if'. If I remove the with clause (and query against some actual table) it compiles, or if I remove IF statements it also compiles. So how can I make them work together?

1 Answer 1

1

You cannot use IF like this in the context of an SQL query. Try using the following instead:

DECLARE @result float, @result1 float, @result2 float

WITH tempTable AS
(
   SELECT * from TableA          
)
SELECT @result1 = sum(case when @inputType = 1 then t.result1 else 0 end), 
       @result2 = sum(case when @inputType = 2 then t.result2 else 0 end)
FROM tempTable

IF @inputType = 1
   SET @result = @result1
ELSE 
   SET @result = @result2

RETURN @result
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your help! I saw in some other posts saying "can't use IF in a query" but it never occured to me that it applies to me. (I thought my usage of if is for flow control not INSIDE query). Anyway, it works now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.