Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute Stored Procedure from a Function

I know this has been asked to death, and I know why SQL Server doesn't let you do it.

But is there any workaround for this, other than using Extended Stored Procedures?

And please don't tell me to convert my function into a procedure...

So what I'm really asking is: Is there ANY way to run a Stored Procedure from within a Function?

EDIT:

Point proven: there is a way around it, but it's so WRONG I wouldn't do it. I'm gonna change it to a Stored Procedure and execute it elsewhere.

like image 689
Smur Avatar asked Jun 14 '11 14:06

Smur


People also ask

Can you execute a stored procedure in a function?

According to Microsoft standard, stored procedures cannot be executed inside the function, but technically it is possible with some tweaks.

How can we execute stored procedures and functions?

To execute a stored procedure or function, you only need to include its object name. Procedures and functions that are created outside of a package are called stored or standalone subprograms. Procedures and functions defined within a package are known as packaged subprograms.

Can we call SP in function in SQL?

Creating a Stored Procedure in SQL Server. A function can be called in a select statement as well as in a stored procedure. Since a function call would return a value we need to store the return value in a variable.

How do you execute a stored procedure?

Expand the database that you want, expand Programmability, and then expand Stored Procedures. Right-click the user-defined stored procedure that you want and select Execute Stored Procedure. In the Execute Procedure dialog box, specify a value for each parameter and whether it should pass a null value.


2 Answers

EDIT: I haven't tried this, so I can't vouch for it! And you already know you shouldn't be doing this, so please don't do it. BUT...

Try looking here: http://sqlblog.com/blogs/denis_gobo/archive/2008/05/08/6703.aspx

The key bit is this bit which I have attempted to tweak for your purposes:

DECLARE @SQL varchar(500)  SELECT @SQL = 'osql -S' +@@servername +' -E -q "exec dbName..sprocName "'  EXEC master..xp_cmdshell @SQL 
like image 119
Tom Chantler Avatar answered Oct 01 '22 11:10

Tom Chantler


Functions are not allowed to have side-effects such as altering table contents.

Stored Procedures are.

If a function called a stored procedure, the function would become able to have side-effects.


So, sorry, but no, you can't call a stored procedure from a function.

like image 23
MatBailie Avatar answered Oct 01 '22 10:10

MatBailie