Stored procedure and Linq to sql - sql-server

If I write a stored procedure and invoke it using Linq-to-SQL and perform (or rather compose) few more queries on the resultant set, how will it be executed? Will the stored procedure execute first and the composed query be executed on the stored procedure's result?
Thanks for any pointers.

What you said is correct. The stored procedure will execute, return a result set (an IEnumerable I think), and then your other queries will execute against the result set.
Note: L2S often has problems getting the type of a stored procedure result set correct. Often times it will create a reference to the stored procedure with no result set (return type of void). And it doesn't seem to be predictable. Because of this, I've stopped querying against stored procedures and query against user-defined functions. I've never had this sort of problem with a UDF.

Related

Will TSQL return faster results than stored procedure in SQL Server

I have a stored procedure that works fine previously. It took 4 to 5 secs to get the results.
I didn't used this stored procedure for the past two months. When I call the same procedure now it takes more than 5 minutes to produce the result.
(There is no records populated to my source tables in the past two months)
I converted the stored procedure and executed as TSQL block it is back to normal. But when I convert back to stored procedure again it is taking more than 5 minutes.
I am wondering why it is behaving like this. I used 6 table variables. I just populating those table variables to get the desired results by joining all those.
I already tried the below options
With Recompile at the stored procedure level
DBCC FREEPROCCACHE
DBCC DROPCLEANBUFFERS
sp_updatestats
but there is no improvement. When I execute it as TSQL it works fine.
Please suggest me any ideas to optimize the stored procedure.
In your queries, add OPTION(OPTIMIZE FOR UNKNOWN) (as the last clause) to prevent parameter sniffing. For syntax and explanation, see the documentation on Query Hints.
What SQL Server does the first time it runs a Stored Procedure is optimize the execution plan(s) for the parameters that were passed to it. This is done in a process that is called Parameter Sniffing.
In general, execution plans are cached by SQL Server so that SQL Server doesn't have to recompile each time for the same query. The next time the procedure is run, SQL Server will re-use the execution plan(s) for the queries in it... However, the execution plan(s) might be totally inefficient if you call it (them) with different parameters.
The option I gave you will tell to the SQL compiler that the execution plan should not be optimized for specific parameters, but rather for any parameter that is passed to the Stored Procedure.
To quote the documentation:
OPTIMIZE FOR UNKNOWN
Instructs the query optimizer to use statistical data instead of the initial values for all local variables when the query is compiled and optimized, including parameters created with forced parameterization.
In some cases Stored Procedures can benefit from Parameter Sniffing, in some cases they don't. For the Stored Procedures that don't benefit from Paramater Sniffing, you can add the option to each query that uses any of the parameters of the Stored Procedure.
You may have bad execution plan associated with that proc.
Try this one
DBCC FREESYSTEMCACHE ('ALL') WITH MARK_IN_USE_FOR_REMOVAL;
You may also find this interesting to read
http://www.sqlpointers.com/2006/11/parameter-sniffing-stored-procedures.html

difference between procedure and stored procedure sql server?

What is the difference between a procedure and a stored procedure on sql server?
There is no difference. There is no concept of "unstored" procedures in SQL Server.
CREATE PROCEDURE
Will create a stored procedure
select * from sys.procedures
will show you the stored procedures.
This is as opposed to sending adhoc sql statements or prepared sql statements.
A procedure is a specified series of actions, acts or operations which have to be executed in the same manner in order to always obtain the same result under the same circumstances
A stored procedure is a subroutine available to applications accessing a relational database system. Stored procedures (sometimes called a proc, sproc, StoPro, or SP) are actually stored in the database data dictionary.
n a procedure you have to start the transaction manually, allowing the rollback manually and stuff like that.
In a stored procedure, usually the DBA system takes care of the main transaction in case of errors. You can even use atomic transactions to keep your information consistent.
Then, A stored procedure is execute a bit faster than a single procedure because of the indexing in the dba.
If it's an actual procedure, in the database, it's a stored procedure -- regardless of whether people pronounce the "stored" part.
Stored procedures are in opposition to the client's issuing the SQL statements of the procedure one by one. That's what an un-"stored procedure" would be.

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.

sql stored procedure clear resultsets

Can I clear the multiple result sets that a stored procedure has already gathered so that the next result set that is created becomes the very first result set returned by the procedure?
this would depend on the Database. In Sql Server, once the result set is sent, it is gone. The receiving application/code must deal with it. If you need to have logic like this, gather the results into a temp table and only return what is needed at the end of the procedure.
As KM said it depends a bit on the database. Can you explain how your stored procedure gather multiple result sets? Are you achieving this via multiple unions or by creating a dynamic sql statement ?

Resources