I tried to create a function with a conditional calculation before the RETURN
statement, but SSMS states that there is an incorrect syntax near 'BEGIN IF @param2 IS NULL'
and I can't figure out what is wrong with this code:
CREATE FUNCTION ConditionalFunction
(
@input1 VARCHAR(20),
@input2 VARCHAR(20)
)
RETURNS TABLE
AS BEGIN
IF @input2 IS NULL
BEGIN
SET @input2 = field
FROM table1
WHERE filter = @input1
END
RETURN
(
SELECT field1, field2
FROM table2
WHERE filter1 = @input1
AND filter2 = @input2
)
END
My goal is to be able to call it either
ConditionalFunction('Foo',NULL)
or
ConditionalFunction('Foo','Bar')
In a way that the first call will make it detect a default value for @input2
based on @input1
.
I wrote this code based on this answer.
This is SQL Server 13. Could you please tell me if there is anything I can do to make it compile?
N.B: I obviously replaced real names with generics, but the code structure remains the same