I want to create a function in SQL Server 2005 that returns a table which the query is passing from my program…
But when I create that function with this script:
CREATE FUNCTION fn_test (@source varchar(255))
RETURNS TABLE AS
RETURN
EXECUTE (@source)
The script is showing error message
Incorrect syntax near the keyword “EXECUTE`
It’s perfectly correct – you’re not allowed to execute arbitrary SQL as part of an inline table valued function:
If you need(*) to have a facility to pass arbitrary SQL into a SQL Server object and have it execute it, use a stored procedure rather than a function. Functions are not meant to alter the state of the database, but arbitrary SQL can do… arbitrary things.
(*)You don’t.
As a procedure, it would be:
But as is probably evident at this point – if you want to execute arbitrary SQL stored as strings, you may as well just directly call
EXECUTEon them. That’s part of what I was alluding to when I put my (*) in. The other part is – why send it in a string variable to the server at all – why not just send the SQL you want to execute, if you’re going to run arbitrary SQL on the server anyway.