Call Stored Procedure from a Function

  • ishaan99 (12/8/2008)


    Has anyone tried calling a stored procedure from a user defined function. I have a procedure as Proc_XXX with 7 parameters if i do exec Proc_XXX(null,null,null,null,null,'1/1/1998','1/1/2007') i am getting the result set. Is it possible to have the same results when calling through a function .

    call Proc_XXX(null,null,null,null,null,'1/1/1998','1/1/2007')

    any help on this will be greatly appreciated. TIA

    Hi there. This technically can be done, to varying degrees based on the method you use. However, I will reiterate what others here have cautioned about:

  • If you attempt any side-effecting operations, it could produce unexpected results.
  • If you are doing a read-only operation (e.g. a SELECT) then it should be ok (see note below)
  • There are three ways that I know of to do this:

  • OPENROWSET / OPENQUERY (mentioned by SwePeso): this will make an external connection that will be a new session (i.e. @@SPID) so no shared share info such as local temp tables (e.g. #tmp) or CONTEXT_INFO. Global temp tables are accessible (e.g. ##tmp). There will also be some additional, and possibly larger-impacting security configuration needed depending on which of those two you are using. This method can allow for changing the state of the database!
  • SQLCLR using standard / regular external connection: this will make an external connection that will be a new session (i.e. @@SPID) so no shared share info such as local temp tables (e.g. #tmp) or CONTEXT_INFO. Global temp tables are accessible (e.g. ##tmp). The only security configuration needed is setting the Assembly to EXTERNAL_ACCESS, but that configuration affects only the Assembly so a fairly narrow security impact. This method can allow for changing the state of the database!

    NOTE: If changing the state of the database, you need to make sure to mark the .Net method as IsDeterministic=false (which is the default).

  • SQLCLR using in-process Context Connection: this is the only option for tapping into the internal connection. This is part of the same session (i.e. same @@SPID) so you do have access to local temp tables (e.g. #tmp) and CONTEXT_INFO! No security changes are needed as this can be done with an Assembly marked as SAFE. This method only allows for read-only interactions and cannot change the state of the database. This method has the same restrictions as T-SQL User-Defined Functions (well, with the obvious exception of not being able to call Stored Procedures).
  • I have detailed a large portion of this info, and even provided an example of both SQLCLR options, in my article (here on SSC): Stairway to SQLCLR Level 2: Sample Stored Procedure and Function[/url]

    Take care,

    Solomon...

    SQL#https://SQLsharp.com/ ( SQLCLR library ofover 340 Functions and Procedures)
    Sql Quantum Lifthttps://SqlQuantumLift.com/ ( company )
    Sql Quantum Leaphttps://SqlQuantumLeap.com/ ( blog )
    Info sitesCollations     •     Module Signing     •     SQLCLR

  • SwePeso (12/10/2008)


    I have a function where I call "sp_who2" and take database and username as parameters to the function.

    Works great.

    Hi there. I just wanted to mention that while OPENROWSET does indeed work here, and that it is a read-only operation so it should be stable, there is a quicker and simpler solution. If you do the following:

    EXEC master.dbo.sp_helptext N'sp_who2'

    you will see the full query logic of sp_who2. Be warned: it ain't pretty ;-). But, it does provide for seeing how they went about getting that data. So, you could just write a new Stored Procedure, passing in any filter params that you want, that does more than your setup of passing in database name and username to adjust the query.

    That being said, it would probably be even better to just query the new DMVs directly :-). The point being: many of the Microsoft provided "sp_" procs are in plain text so you can get the definition to learn what they are doing.

    Take care,

    Solomon..

    SQL#https://SQLsharp.com/ ( SQLCLR library ofover 340 Functions and Procedures)
    Sql Quantum Lifthttps://SqlQuantumLift.com/ ( company )
    Sql Quantum Leaphttps://SqlQuantumLeap.com/ ( blog )
    Info sitesCollations     •     Module Signing     •     SQLCLR

  • Can you share the code that does this? Calling sp_who from within a function?

  • Nuhamovici (3/19/2015)


    Can you share the code that does this? Calling sp_who from within a function?

    Why? What could you possibly gain from calling a stored proc from within a function? You should instead get rid of the function entirely.

    If you can explain what you are trying to do we can help you find a better approach than calling a stored proc from a function.

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/

  • Sean Lange (3/19/2015)


    Nuhamovici (3/19/2015)


    Can you share the code that does this? Calling sp_who from within a function?

    Why? What could you possibly gain from calling a stored proc from within a function? You should instead get rid of the function entirely.

    If you can explain what you are trying to do we can help you find a better approach than calling a stored proc from a function.

    It makes it easy to filter when you're in a hurry... real easy.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

  • Jeff Moden (3/19/2015)


    Sean Lange (3/19/2015)


    Nuhamovici (3/19/2015)


    Can you share the code that does this? Calling sp_who from within a function?

    Why? What could you possibly gain from calling a stored proc from within a function? You should instead get rid of the function entirely.

    If you can explain what you are trying to do we can help you find a better approach than calling a stored proc from a function.

    It makes it easy to filter when you're in a hurry... real easy.

    I hope I am just not hearing the sarcasm sound in your response thanks to the internet...if not...well...

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/

  • Nuhamovici (3/19/2015)


    Can you share the code that does this? Calling sp_who from within a function?

    I cannot think of a reason why anyone would even be using sp_who, let alone want to go through the trouble of setting this up when you can get that information (and more) more easily by simply selecting from one or more of the following DMVs:

    • sys.dm_exec_sessions
    • sys.dm_exec_requests
    • sys.dm_exec_connections

    Take care,

    Solomon..

    SQL#https://SQLsharp.com/ ( SQLCLR library ofover 340 Functions and Procedures)
    Sql Quantum Lifthttps://SqlQuantumLift.com/ ( company )
    Sql Quantum Leaphttps://SqlQuantumLeap.com/ ( blog )
    Info sitesCollations     •     Module Signing     •     SQLCLR

  • Sean Lange (3/19/2015)


    Jeff Moden (3/19/2015)


    Sean Lange (3/19/2015)


    Nuhamovici (3/19/2015)


    Can you share the code that does this? Calling sp_who from within a function?

    Why? What could you possibly gain from calling a stored proc from within a function? You should instead get rid of the function entirely.

    If you can explain what you are trying to do we can help you find a better approach than calling a stored proc from a function.

    It makes it easy to filter when you're in a hurry... real easy.

    I hope I am just not hearing the sarcasm sound in your response thanks to the internet...if not...well...

    Gosh no. Apologies for the way that came across. No sarcasm or irony there. I have actually used the technique in a pinch. I don't use it for sp_who specifically, though, for the very reason that Solomon posted.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

  • Jeff Moden (3/19/2015)


    Sean Lange (3/19/2015)


    Jeff Moden (3/19/2015)


    Sean Lange (3/19/2015)


    Nuhamovici (3/19/2015)


    Can you share the code that does this? Calling sp_who from within a function?

    Why? What could you possibly gain from calling a stored proc from within a function? You should instead get rid of the function entirely.

    If you can explain what you are trying to do we can help you find a better approach than calling a stored proc from a function.

    It makes it easy to filter when you're in a hurry... real easy.

    I hope I am just not hearing the sarcasm sound in your response thanks to the internet...if not...well...

    Gosh no. Apologies for the way that came across. No sarcasm or irony there. I have actually used the technique in a pinch. I don't use it for sp_who specifically, though, for the very reason that Solomon posted.

    No need to apologize at all. 😉 I still can't really grasp how this would be useful. I guess I need to read up a bit more here but a proc being called from a udf has a particularly bad code smell to my nose.

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/

  • Thanks for the reply.

    I agree this is something we should "never" do. It's considered a 'bad practice'.

    Also, it's not the sp_who stored proc I was interested. It could be any proc for that matter. I wanted

    see the "technique" of trying to do this.

    Why would anyone want to do this? Good question.

    Imagine you had an "old legacy" ODBC type of application, that let's user type in queries..with the limitation

    that they follow the "select field_name from table where condition", It won't allow you to type a "sp_who"

    or anything like that. However, it does let you run a function within the select. I need to run some stored procedures

    but the tool won't let me. I was thinking of "cheating" and trying to wrap the stored proc in a function. Then I would

    invoke it select my_function(stored_proc) from table_with_1_row.

    Thanks for any suggestions.

  • Heh... I guess that if enough people say it should "never" be done and that it's a "bad practice" without a detailed explanation as to why, we can actually write the 5 monkeys experiment at the human level. 😉

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

  • Yes, it looks like this is so evil, it shouldn't even be attempted!

  • Nuhamovici (3/24/2015)


    Yes, it looks like this is so evil, it shouldn't even be attempted!

    Uh huh. And AC electricity wouldn't be the norm if people listened to the naysayers that said it shouldn't even be attempted. 😉

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

  • Jeff Moden (3/24/2015)


    Nuhamovici (3/24/2015)


    Yes, it looks like this is so evil, it shouldn't even be attempted!

    Uh huh. And AC electricity wouldn't be the norm if people listened to the naysayers that said it shouldn't even be attempted. 😉

    Hey! Tesla was right - long live Tesla! Look at what he'd done for cars.


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St

  • about 15 years ago I had the privilege of doing some projects using Interbase and later Firebird, and there you could just select from a stored procedure, or join with a stored procedure without the need to wrap it in a function

    SQLServer has evolved enormously since 6.5, and though I must say functions do cover most of the needs I still miss that functionality from time to time 🙂

    I wonder why MS never implemented this

    Dirk

  • Viewing 15 posts - 16 through 30 (of 30 total)

    You must be logged in to reply to this topic. Login to reply