How can I create a Table-Valued User-Defined Function in SQL Server that takes an input parameter for an IN clause?
I'm trying to write this very simple function:
CREATE FUNCTION dbo.MyTableValuedFunction (@myList VARCHAR(MAX))
RETURNS @myTable TABLE (
[ID] INT,
[Name] VARCHAR(MAX)
)
AS
BEGIN
INSERT INTO @myTable
SELECT ID, Name FROM MyTable WHERE ID IN (@myList)
RETURN
END
A popular generative AI is suggesting to build a sql string and use 'EXEC'
CREATE FUNCTION dbo.MyTableValuedFunction (@myList VARCHAR(MAX))
RETURNS @myTable TABLE (
[ID] INT,
[Name] VARCHAR(MAX)
)
AS
BEGIN
DECLARE @sql NVARCHAR(MAX)
SET @sql = 'SELECT ID, Name FROM MyTable WHERE ID IN (' + @myList + ')'
INSERT INTO @myTable
EXEC sp_executesql @sql
RETURN
END
But when I try to run it, I receive the following error: Invalid use of a side-effecting operator 'INSERT EXEC' within a function.
Is there any way to use an IN clause with a list as an input parameter in a Table-Valued User-Defined Function?