Invalid use of side-effecting operator 'INSERT EXEC' within a function
use this code to join rowset to delimited single value

sql,

use this code instead:

    DECLARE @IDs NVARCHAR(max)=''

    SELECT @IDs += ID +','
    FROM dbo.SomeTable

select @IDs


you can add where clause and design your query to return  rowset with CTE and UNION ALL