Skip to content
Advertisement

Table variable in User Defined Function SQL Server and performance of UDF

I have an UDF like this

CREATE FUNCTION Lob_function
(
    @policy NVARCHAR(MAX)
    @table  Table
)
RETURNS NVARCHAR(MAX)
AS 
BEGIN
select @policy= 
case
when @policy like '%AMM%' then 'AMM'
when @policy like '%MOT%' then 'MOT'
when @policy like '%MOX%' then 'MOX'
when @policy not like '00%' then LEFT(@policy,3)
end
from @table
return @policy
END;

I want to use my UDF for various cases like :

Select Lob_function (@policy, @table) from @table.

It appears an error on @table Table, when I replace @table by a fixed table, my UDF can be executed but very slowly compared with a normal Select statement.

Advertisement

Answer

You can’t really do what you want.

First, you cannot pass tables as parameters into functions. As the documentation explains:

Parameters can take the place only of constants; they cannot be used instead of table names, column names, or the names of other database objects.

In theory, you could use dynamic SQL to construct a query and run it. Unfortunately, the only use of execute is for extended functions. This is a little buried in the documentation, but it is there:

User-defined functions cannot make use of dynamic SQL or temp tables. Table variables are allowed.

That really doesn’t leave any good options. You might try to think of another approach that doesn’t require storing related data in multiple different tables. Or perhaps you can use a stored procedure instead of a UDF.

There are some very arcane work-arounds, which involve using an extended stored procedure or CLR to execute a batch command which in turn passes a query into the database. That is really complicated, prone to error, and I’ve never actually seen it used in production code.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement