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?