Can we call a stored procedure from a function in SQL? What's the reason?
A:
Quick answer: No.
Why: A stored procedure does not produce any output that can be re-used inside SQL.
leppie
2010-08-23 10:41:51
There are output parameters, and you can insert the result of a stored procedure into a table
Andomar
2010-08-23 10:44:05
+2
A:
Functions can only read data, they can't update or change anything. It follows that functions are not allowed to call stored procedures.
Andomar
2010-08-23 10:43:16
A:
To be efficient a function should be deterministic, i.e. the output should only be depending on the input, so that the result can be cached.
If you want to call a stored procedure from a function, yout have to specifically make the function non-deterministic.
Guffa
2010-08-23 10:43:22
+1
A:
Yes.
You can do this with a bit of a hack involving openrowset
but it's not recommended as it will open a new connection.
CREATE FUNCTION dbo.test ()
RETURNS varchar(200)
AS
BEGIN
RETURN (Select top 1 [Name] from
OPENROWSET('SQLNCLI','Server=.\SQL2008;Trusted_Connection=yes;','SET NOCOUNT ON;SET FMTONLY OFF;EXEC MASTER..SP_HELP')
)
END
GO
SELECT dbo.test()
Martin Smith
2010-08-23 12:07:07