views:

35

answers:

4

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
There are output parameters, and you can insert the result of a stored procedure into a table
Andomar
+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
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
Virtually all UDF's depend on the content of one or more tables, so they're not deterministic at all
Andomar
@Andomar: Not at all. There are plenty of UDF's that are deterministic.
Guffa
+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