Can we call a stored proc from a function?

前端 未结 4 1055
梦谈多话
梦谈多话 2020-12-20 09:42

Can we call a stored procedure from a function in SQL? What\'s the reason?

相关标签:
4条回答
  • 2020-12-20 10:03

    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.

    0 讨论(0)
  • 2020-12-20 10:06

    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()
    
    0 讨论(0)
  • 2020-12-20 10:09

    Functions can only read data, they can't update or change anything. It follows that functions are not allowed to call stored procedures.

    0 讨论(0)
  • 2020-12-20 10:19

    Quick answer: No.

    Why: A stored procedure does not produce any output that can be re-used inside SQL.

    0 讨论(0)
提交回复
热议问题