Click here to Skip to main content
15,892,674 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi Friends,

I have a doubt regarding in Stored procedure and Sql
My question which way is good to write in csharp application
1) Directly Sql queries in Source code or
2) Calling the Stored Procedure.

Can anyone explain on this topic and give me a diff on Sp Vs Sql in C#
ex:Suppose if same query how much time it will take to run sql in csharp and SP in csharp too..

Thanks
Bhavani
Posted

There is no "one answer" to this: either way the execution is pretty much the same, because an SP is just a sequence of instructions that is executed in the same way that it would be if you entered them as a string and sent them over as an SqlCommand. The SP will be precompiled is all, which might save a small (and I do mean small) amount of processing time at the SQL server end. but not much!

It's a balance between clarity and structure: some people like to put even trivial SELECT or UPDATE statements into an SP, but I feel that makes code harder to read as you can't tell what an SP is doing without consulting SSMS and looking - "inline" code for simple stuff is a lot easier to maintain.

Generally, I use an SP where it's complex: where it's too easy to make a mistake, or you don't need to know exactly how it works, just get the results you wanted. For example:
SQL
SELECT a.Name, b.EpCount
FROM Serials a
JOIN
  (SELECT SerialId, Count(SerialNo) AS EpCount
   FROM Episode GROUP BY SerialId) AS b
ON a.Id = b.SerialId
is an SP called CountEpisodes because it returns each series of a TV show together with the number of episodes - it's something I use in a few places, and it's a little complex to work out. So get it right once, create an SP and it becomes trivial next time.
 
Share this answer
 
One great advantage with using SP is that the client code (in this case in c#) can be isolated from the database structure.

This means that the same client can be used for different database implementations and different databases, such as Oracle, MS SQL and MySQL.

The database can change internally as much as is necessary and the client will know no difference as long as the signature of the stored procedure is kept intact.

The final choice is due to need and possible future changes.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900