With a stored procedure in a database, would the following situation be true?
I have a procedure that queries a very large table, and in my query I call the stored procedure, and follow it with a WHERE record_class = "THE ONE IM LOOKING FOR".
In the stored procedure I'm not limiting the records by the record_class, so does the WHERE clause do anything other than filter the results that the procedure returns?
In other words, if I wanted to speed up the results because it takes too long, would adding a parameter for the record_class to the procedure and selecting only those when it performs its tasks be quicker than using the WHERE clause?
Your analysis is completely true, if you apply the condition directly in your stored procedure instead of outside it will for sure be more performant.
In the first situation, your procedure will return every rows without applying your condition (this condition is completely unknown for the procedure) and this result will then be filtered with your WHERE clause.
Depending on your needs, the best solution may be to define a parameter for your stored procedure so you can pass this parameter at execution and the result will be filtered. I don't know exactly what is the purpose of your procedure but by doing so, you'll keep the possibility to execute the same procedure for multiple situations (you simply need to pass the record_class you want to filter the result or let it NULL if you want the entire data).
This approach requires a little modification to your procedure (adding a parameter) and a modification of your query (adding the WHERE clause that filters the result if needed).
Hope this will help you.
Related
I'm writing a stored procedure which checks for the existence of various tables in various databases, as well as the permissions that the user executing the stored procedure has on those tables. The stored procedure itself resides within a user database (i.e. it's not in the Master db).
To perform my checks, my stored procedure contains lots of SELECT statements. Each of those obviously returns a record set. What I would like is to somehow suppress these record sets so that they are not returned by the stored procedure, and instead return my own, single record set which is just a collection of messages relating to each check the stored procedure performs.
I think the obvious answer is to use a table-valued function instead, but I've not been able to recreate my tests successfully in a Function as they appear in the stored procedure. For starters, I'm having to use temporary tables (not possible in a function) and dynamic SQL (not very compatible with table parameters).
I think I've basically got two choices:
Rewrite my stored procedure as a function and figure out how to do the checks a different way.
Continue using my stored procedure and use an OUTPUT parameter to return my result messages, probably as a delimited string, and in the associated ASP.NET application just ignore all the record sets the stored procedure returns .
Neither of these solutions is very satisfactory. Before I spend any more time pursuing either one, is there a way to discard the record sets produced by the SELECT statements in a stored procedure and explicitly define what record I want it to return?
Hmm, I only can speculate here...
Are you using something like
SELECT ...;
IF ##rowcount > 0
BEGIN
...
END;
?
Then you can rewrite it using something like
IF EXISTS (SELECT ...)
BEGIN
...
END;
or
DECLARE #variable integer;
SELECT #variable = count(*) ...;
IF #variable > 0
BEGIN
...
END;
In general point the results of your queries to a target (variable, table, expression, ...), then they don't get outputted.
And then just execute the query for your desired result in the end.
In my opinion, here is almost no reason to have stored procedures produce record sets. That is what stored functions are for. On occasion, it is needed, because of the use of dynamic SQL or other stored procedures, but not as a general practice. Much, much too often, I see stored procedures being used where stored functions or views are more appropriate.
What should you do? Even SELECT statement in the stored procedure should be one of the following:
Setting (local) variables.
Saving the results in a temporary table or table variable.
The logic for the stored procedure should be working on the local variables. The results should be returned using OUTPUT parameters.
If you need to return rows in a tabular format, you can do that using tables explicitly (such as a global temporary table or real table). Or, you can have one SELECT at the end that does return a single result set. However, if you need this and can phrase the stored procedure as a function, that is better in my opinion.
Why stored procedure cannot be used with Select, Where & Having?
I understand a function can serve the purpose - what's the reason why a stored procedure cannot be executed in select?
Blogs are answering you can use UDF. Understand we can use UDF & we are using.
Need a valid reason on stored procedure.
Biggest reasons most likely is that procedures can return any number of result sets and change data. It can have no results, or it can be 100 different results sets with 0 to n rows. It can also depend on your input parameters. Stored procedure can also affect the underlying data, so what would happen if you would use a stored procedure that changes data in the same table you're using it in the where clause? The results sets don't even necessary have names for the columns, so you couldn't refer them in any way.
So, since for procedures would be really complex to implement anything like that, why should it be possible to use them in where etc? You haven't provided any valid reason why they should.
The reason functions exist, is that you can use them for where clauses etc.
I am writing a sql procedure where almost everything will be dynamic including selecting, grouping, ordering by, and where clauses using IN statements. In terms of code reuse, readability, and maintenance it makes a lot of sense to just pass in an sql query as a string and execute it. I am writing my procedure right now so that all the relevant data is joined and formatted in a static query and then inserted into a table variable. I then want to pass in sql queries to be executed against the table variable.
This opens me up to sql injection in a big way. I could create table value parameters for each of the many parameter types I am passing in but I don't want to do that. What I would really like to be able to do sandbox my procedure in a such a way that, on the procedure level, it is only possible to do these things I want to allow; ie select from certain tables, but not grant permissions or anything funny like that. Can this be done?
Of course it can be done. It's a simple matter of programming. You would keep rules in tables, and write logic in your stored procedure to query the rules tables, and follow the rules.
It will be a monumental job that will basically amount to you writing custom code to do what SQL Server already does for you if you don't use a generic, dynamic stored procedure.
I wouldn't do it, but you don't have to let that stop you.
Is it possible to create a stored procedure that has parameters which are all optional individually, but at least one of the parameters must be provided?
For example, if I have a procedure that updates a record, I must pass in a record id, and then at least one column to update. The procedure should check to ensure at least one additional parameter/column is provided.
I would put an if statement as the first action.
IF #param1 is null and #param2 isnul and #param3 is null
Begin
--steps tpo raise an error or exit the proc
End
I would do this in my programming language of choice instead of a stored proc. Why? This is the type of logic checking that TSQL is not very good at; the syntax for checking this will be "icky" and it will be slow.
Also, the biggest performance advantage a stored proc gives you is running compiled SQL. In this case, because the SQL needs to be dynamically built, you lose that advantage. Thus, why do it as a stored procedure?
Use the following in where clause
where
(isnull(#param1,0)=0 or id=#param1)
and
(isnull(#param2,'')='' or name=#param2)
I didn't undetstood the difference between Stored Functions and Views.
Using Views in SELECT will execute the query and return the result, but Stored Functions do the same thing, don't they? So what is the difference? When I use Views and when Stored Functions?
View:
A view is a virtual table. It does not physically exist. Rather, it is created by a query joining one or more tables. View returns a table.
Stored procedure: A stored procedure is a group of Transact-SQL statements compiled into a single execution plan.
stored procedures returns Output parameters,return codes (which are always an integer value),
a result set for each SELECT statement contained in the stored procedure or any other stored procedures called by the stored procedure,a global cursor that can be referenced outside the stored procedure.
key benefits of stored procedure are Precompiled execution, reduced client/server traffic,efficient reuse of code, programming abstraction and enhanced security controls.
Update:
A stored function is a named PL/SQL Block which is similar to a procedure. The major difference between a procedure and a function is, a function must always return a value, but a procedure may or may not return a value.
1) Return Type: The header section defines the return type of the function. The return datatype can be any of the oracle datatype like varchar, number etc.
2) The execution and exception section both should return a value which is of the datatype defined in the header section
You can have a stored function return the same data a view would in most databases.
The distinction for me is that a function is executed and a view is selected from.
A view will behave as a table.
A view returns a specific pre-defined statement as exactly one result set.
A function returns a single values or a single result set. This however can differ from different types of database.
Several db implementations also have stored procedures where the result can be a single returned value, a result set or several result sets.
Getting simple (PLEASE start reading a book about SQL): A view looks like a table, so you can filter on the results and the filter will efficiently be part of the views execution, or do joins. A SP does not allow this, but a lot more logic. The rest... is in the documentation.
These can never be compares, these have totally different
approach.
A view is a output of a query ,and makes a virtual image of the table,and the input parameters are not accepted.
Main difference is that a Stored Procedure can alter your data, where
as a view only returns it and I believe from a performance point of
view, a stored procedure is better as it caches the execution plan and
will run faster as a result.
storedprocedure/function is a group of sql statements that are pre-executed and it accepts the parameters.it reduces network traffic, gives faster performance, etc.
SQL Functions in programming languages are subroutines used to encapsulate frequently performed logic. these somewhat slow down the performance.
Check these SQL View, SQL Stored Procedures and SQL User-Defined Functions
My Opinion is that SQL Stored Procedure(Stored Functions) are much better to use because it provides custom manipulations on result set also.
From my experiences I'm sharing to you my knowledge:
Don't use views
Better to use a stored procedure(it is compiled sql statement), you can use parametrized procedure as required.
Stored Function is collection of complied sql statement which is faster.
Note: Views is a SELECT statement( with/without JOIN) for a table which select data from table and if we again run a SELECT statement from VIEWS which provide slower result because the internal operation is as ( SELECT * FROM ( SELECT * FROM TargetTable ) )
So, its better to use Stored Function
Update:
Functions are computed values and cannot perform permanent environmental changed to SQL Server (i.e. no INSERT or UPDATE statements allowed).
A Function can be used inline in SQL Statements if it returns a scalar value or can be joined upon if it returns a result set.
Also please see here for performance comparison: SQL-Server Performance: What is faster, a stored procedure or a view?