Use begin..end or call to call stored procedures - database

when I call a stored procedure in an Oracle Database from JDBC I have the following alternatives. Which one is recommended to be used and why?
prepareCall("{call MY_FUN}");
prepareCall"{BEGIN MY_FUN; END;}");
Thanks for your reply.
Regards Johannes

It depends. Using begin..end, you just call an anonymous PL/SQL program block, which in turn calls the stored procedure. When you use call, you call the procedure from SQL. Call has the additional benefit of having the possibility to return values and more. See Oracle Database SQL Language Reference: Call for more information.
That said, if you just call a procedure like this, there's not much of a difference. I think theoretically begin..end would be slightly more efficient, since the procedure itself is PL/SQL and Call, being SQL, would cause an extra context switch between SQL and PL/SQL which has some overhead. But I don't think you will notice this diffence if it even exists.

If you only want to call exactly 1 procedure both statement are probably identical. Using an anonymous PLSQL block however allows you to have a lot more fun. Call more then one procedure for example or use any syntax that is allowed within a PLSQL block.
prepareCall("BEGIN MY_FUN('no-braces-with-begin-end-syntax'); MORE_FUN; A_LOT_MORE_FUN; END;");

You can use any type of procedure according to your requirement. Kindly clarify your requirement.

Related

Why can't I use procedures inside functions in SQL Server?

I know that functions always returns a value and I'll make a sp which return a value as the function returns and want to calling it inside the function. How might I do this?
Some thoughts after your comments above
Generally stored procedures can do almost anything. So it is safer to disallow them
The engine can't reliably work out what your stored procedure does
What about nesting of stored procedures, or recursion, or linked server calls or OPENQUERY calls, and many many other things
What if someone change it later to do some writes?
You can't schema-bind a UDF to a stored procedure
Error throwing/handling is a state change even if the stored procedure is read only
This is how SQL Server behaves for good reasons

Stored procedures and functions

What are the differences between stored procedures and functions.
Whenever there are more input, output parameters i go for stored procedure. If it is only one i will go for functions.
Besides that, is there any performance issue if i use more stored procedures? I am worried as i have close to 50 stored procedures in my project.
How they differ conceptually.
Thanks in advance!
EDITED:-
When i executed a calculation in stored procedure and in functions, i have found that in stored procedures it is taking 0.15 sec, while in function it takes 0.45sec.
Surprisingly functions are taking more time than stored procedures. May be functions are worth for its reusability.
Inline functions executes quicker than strored procedures. I think, this is because multi-select functions can't use statastics, which slows them down, but inline table-value functions can use statistics.
Difference between stored procedure and functions in SQL Server ...
http://www.dotnetspider.com/resources/18920-Difference-between-Stored-Procedure-Functions.aspx
Difference between Stored procedures and User Defined functions[UDF]
http://www.go4expert.com/forums/showthread.php?t=329
Stored procedures vs. functions
http://searchsqlserver.techtarget.com/tip/Stored-procedures-vs-functions
What are the differences between stored procedure and functions in ...
http://www.allinterview.com/showanswers/28431.html
Difference between Stored procedure and functions
http://www.sqlservercentral.com/Forums/Topic416974-8-1.aspx
To decide between using one of the two, keep in mind the fundamental difference between them: stored procedures are designed to return its output to the application. A UDF returns table variables, while a SPROC can't return a table variable although it can create a table. Another significant difference between them is that UDFs can't change the server environment or your operating system environment, while a SPROC can. Operationally, when T-SQL encounters an error the function stops, while T-SQL will ignore an error in a SPROC and proceed to the next statement in your code (provided you've included error handling support). You'll also find that although a SPROC can be used in an XML FOR clause, a UDF cannot be.
If you have an operation such as a query with a FROM clause that requires a rowset be drawn from a table or set of tables, then a function will be your appropriate choice. However, when you want to use that same rowset in your application the better choice would be a stored procedure.
There's quite a bit of debate about the performance benefits of UDFs vs. SPROCs. You might be tempted to believe that stored procedures add more overhead to your server than a UDF. Depending upon how your write your code and the type of data you're processing, this might not be the case. It's always a good idea to text your data in important or time-consuming operations by trying both types of methods on them.

Why can we not execute a stored procedure inside a function in SQL Server

Why can we not execute a stored procedure inside a function when the opposite is possible?
You cannot execute a stored procedure inside a function, because a function is not allowed to modify database state, and stored procedures are allowed to modify database state.
This is by definition (see CREATE FUNCTION - Limitations and Restrictions).
User-defined functions cannot be used to perform actions that modify the database state.
A stored procedure might modify database state, or it might not. But the SQL Server compiler shouldn't have to analyze the stored procedure to know whether or not it modifies database state. Therefore, it is not allowed to execute a stored procedure from within a function.
Functions exist to simply calculate something, a value or a table result, nothing more than that. These functions can be called within a SELECT query for instance, e.g.
SELECT calculate_something(a) FROM some_table;
Now consider what would happen if the function calculate_something were allowed to execute a stored procedure which would delete all rows in some_table. Your intention is to calculate something using the value of the some_table.a columns, but you end up... deleting all rows in some_table. That is clearly not something you want to happen.
I know this is already been answered but in SQL server the function is not suppose to change the data but the procedure is meant to.
In addition to this i like to add that we cannot select a procedure or put it in a where clause but we can do this with a function.
We use function to shorten the code so its greatly helpful as it reduces a lot of query for the coder.
Hope this helps.
I suspect this is because the execution of a function is not supposed to modify data in any way, and allowing you to run a stored procedure would let you do this...
You would need to change your stored procedure to a Function to call it from within a Function.
Or, one way is to use xp_cmdshell to call a batch file where the batch file contains the execute procedure statement. In the function you can call the extended proc.
eg.
Create Function...
EXEC master.sys.xp_cmdshell 'C:\test.bat'
RETURN...
I am in no way saying that this is good practice but am just saying it's a possibility.
We cannot call store procedure within a function. However, we can call a function within a store procedure.
Functions are extremely limited. They cannot perform any operation in any way that can change data. This means that you can't use dynamic sql or call other objects (except functions)
Some restrictions are their for functions,like (i) it should not change any table structure .It should readonly table. But Stored Procedure can change. Stored procedure can do any changes. So we cant call a Stored Procedure from function.
We can call procedure inside function but that function cannot be called through select statement.The function works fine if you call it through another calling program.Same is the case with dml operations.Functions can have dml operations but it cannot be called through select statement.Whereas if you call the function through another program, the dml gets executed
Technically, calling a stored procedure from a function is possible.
But remember the purpose of the stored procedure and functions.
Purpose of function: The function is used to compute a value and hence must return a value. A function can be called from a select statement as long as it does not alter data. (Permanent table data, not temp tables)
Purpose of Stored procedure: The stored procedure is used to execute business logic and hence may or may not return a value.

Changes to a table-valued function called by a stored procedure are not recognized?

I have a stored procedure sp that calls a table-valued function tvf. Sometimes I modify the tvf but when subsequently executing sp, the output from sp is the same as before the modification. It seems like it is cached or compiled or something. If I make some dummy change to the sp, then I get the right output of the sp.
Is there some way, I can overcome this problem? In Oracle it is possible to re-compile all stored procedures, but I haven't been able to figure out how to do this in SQL Server?
Any help is highly appreciated.
You can use sp_recompile to recompile a stored procedure but afaik, what you describe shouldn't happen.
Could you post the udf? Only scenario I can think of would be when the udf always returns the same result, regardless of input parameters.

What is the best way of determining whether our own Stored procedure has been executed successfully or not

I know some ways that we can use in order to determine that whether our own Stored procedure has been executed successfully or not. (using output parameter, putting a select such as select 1 at the end of the stored procedure if it has been executed without any error, ...)
so which one is better and why?
Using RAISERROR in case of error in the procedure integrates better with most clients than using fake out parameters. They simply call the procedure and the RAISERROR translates into an exception in the client application, and exceptions are hard to avoid by the application code, they have to be caught and dealt with.
Having a print statement that clearly states whether the SP has been created or not would be more readable.
e.g.
CREATE PROCEDURE CustOrdersDetail #OrderID int
AS
...
...
...
GO
IF OBJECT_ID('dbo.CustOrdersDetail') IS NOT NULL
PRINT '<<< CREATED PROCEDURE dbo.CustOrdersDetail >>>'
ELSE
PRINT '<<< FAILED CREATING PROCEDURE dbo.CustOrdersDetail >>>'
GO
SP is very much like a method/subroutine/procedure & they all have a task to complete. The task could be as simple as computing & returning a result or could be just a simple manipulation to a record in a table. Depending on the task, you could either return a out value indicating the result of the task whether it was a success, failure or the actual results.
If you need common T-SQL solution for your entire project/database, you can use the output parameter for all procedures. But RAISEERROR is the way to handle errors in your client code, not T-SQL.
Why don't use different return values which then can be handled in code?
Introducing an extra output paramter or an extra select is unnecessary.
If the only thing you need to know is whether there is a problem, a successful execution is good enough choice. Have a look at the discussions of XACT_ABORT and TRY...CATCH here and here.
If you want to know specific error, return code is the right way to pass this information to the caller.
In the majority of production scenarios I tend to deploy a custom error reporting component within the database tier, as part of the solution. Nothing fancy, just a handful of log tables and a few of stored procedures that manage the error logging process.
All stored procedure code that is executed on a production server is then encapsulated using the TRY-CATCH-BLOCK feature available within SQL Server 2005 and above.
This means that in the unlikely event that a given stored procedures were to fail, the details of the error that occurred and the stored procedure that generated it are recorded to a log table. A simple stored procedure call is made from within the CATCH BLOCK in order to record the relevant details.
The foundations for this implementation are actually explained in books online here
Should you wish, you can easily extend this implementation further, for example by incorporating email notification to a DBA or even an SMS alert could be sent dependent on the severity of the error.
An implementation of this sort ensures that if your stored procedure did not report failure then it was of course successful.
Once you have a simple and robust framework in place, it is then straightforward to duplicate and rollout your base implementation to other production servers/application platforms.
Nothing special here, just simple error logging and reporting that works.
If on the other hand you also need to record the successful execution of stored procedures then again, a similar solution can be devised that incorporates log table/s.
I think this question is screaming out for a blog post……..

Resources