Subquery as parameter into SQL Server UDF

338 views Asked by At

My question is similar to this.

I made a scalar function like follows:

CREATE FUNCTION [dbo].[MyFunction](@table [TableModel] READONLY)
RETURNS DECIMAL(18, 6) AS
BEGIN
    DECLARE @sql NVARCHAR(MAX), @params NVARHCAR(MAX), @value DECIMAL(16, 8);
    SELECT @sql = formula, @params = params FROM formulas WHERE id = (SELECT TOP 1 id_formula FROM @table)
    EXEC sp_executesql @sql, @params, @table=@table, @value=@value OUTPUT;
    RETURN @value;
END

Where a formula SQL could be something like:

SELECT @value = SUM(value) / AVG(value) FROM @table

And it could have more columns if needed.

The model table looks like so:

CREATE TYPE [dbo].[TableModel] AS TABLE(
    [formula] INT NOT NULL,
    [value] DECIMAL(16, 8) NOT NULL
)

And I want to use it like so:

SELECT  od.id, od.col1, od.col2, 
        dbo.MyFunction((SELECT id.formula, id.value FROM #raw_data id WHERE id.id = od.id)) as result
FROM    #data od
GROUP BY od.id, od.col1, od.col2

Where the ID unique and multiple rows will have the same id.

Basically, what I'm trying to do in a single query I want to call a function that has a table parameter. But I want this table to be a subquery.

I'm aware that you can call the function with a table variable as mentioned in this answer.

Is this possible in any way? I'm having this error at executing:

Msg 116, Level 16, State 1, Line 30
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.

0

There are 0 answers