MikeBronner
Programmer
My basic question is: how can I execute dynamic SQL (declaring a cursor from dynamic SQL) from within a user-defined function?
Here's the function:
And here's the calling code:
And here's the error message:
I've read over and over that I can't run dynamic SQL from within a UDF (which was intentional design from MS for security and integrity purposes). My problem with that is that I don't know how to run a stored procedure inside a SQL statement either (i.e. in the calling code) instead of using a user-defined function.
Any ideas?
Take Care,
Mike
Here's the function:
Code:
ALTER FUNCTION concat_results
(
@sql AS VARCHAR(1000)
,@delimeter AS VARCHAR(255)
,@pre_text AS VARCHAR(255)
,@post_text AS VARCHAR(255)
)
RETURNS VARCHAR(8000)
AS
BEGIN
DECLARE @result VARCHAR(8000)
,@cursor CURSOR
,@temp VARCHAR(1000)
SET @sql = 'SET @cursor CURSOR INSENSITIVE FOR ' + @sql
EXEC @sql
OPEN @cursor
FETCH NEXT FROM @cursor INTO @temp
WHILE @@FETCH_STATUS = 0
BEGIN
SET @result = @result + @delimeter + @temp
FETCH NEXT FROM @cursor INTO @temp
END
SET @result = SUBSTRING(@result, 1, LEN(@result) - LEN(@delimeter))
RETURN @result
END
GO
And here's the calling code:
Code:
SELECT id
,name
,dbo.concat_results('SELECT name FROM attributes a, role_attributes ra WHERE a.id = ra.attribute_id AND ra.role_id = ' + CONVERT(VARCHAR(20), id) + ' ORDER BY name', ', ', '', '') AS attributes
FROM roles
ORDER BY name
And here's the error message:
Server: Msg 558, Level 16, State 2, Procedure concat_results, Line 16
Remote function calls are not allowed within a function.
I've read over and over that I can't run dynamic SQL from within a UDF (which was intentional design from MS for security and integrity purposes). My problem with that is that I don't know how to run a stored procedure inside a SQL statement either (i.e. in the calling code) instead of using a user-defined function.
Any ideas?
Take Care,
Mike