What I mean is if I have two ways to write a SQL query:
write it inside SQL as a stored procedure and execute it from C#
build a query in C# then execute the query so it does not exist in my database
Which is better and why?
What I mean is if I have two ways to write a SQL query:
write it inside SQL as a stored procedure and execute it from C#
build a query in C# then execute the query so it does not exist in my database
Which is better and why?
"Better" is opinion-based. But there are hard facts:
Stored procedures can be compiled by the database. That means you have syntax checking. Comma missing or field mistyped? In a stored procedure this will bring up a compile time error, in your program it will be a runtime error.
SQL code that is in the program can not be optimized beforehand. For the database, a statement from the program is random. It may be cached and maybe the database is intelligent enough to see that the statement never changes, but if it's inside a compiled stored procedure, it can be compiled and prepared. Once on compile. Not once per call.
If you change the database, your stored procedures will become invalid. Right there on the spot. It's obvious. If you have code in the program, it may generate a runtime error when the user clicks a button three weeks later.
Having it all in code is easier to handle for the developer.
And there are probably more pros and cons. You will have to weight them all and decide for yourself.
Edit:
This question is tagged sql-server and therefore the comments are appropriate. Please note that my answer above was programming language and DBMS agnostic. They describe what can be done. MS-SQL at the time of this post is a pretty good DBMS but there are others that existed for decades and are way more optimized than MS SQL. MS SQL may not support those features I'm talking about.
If you put your SQL in code, from the perspective of the DBMS it's a new query every time. It may use statement caching to optimize it for every call that is inside it's caching mechanism scope. However, it will never be able to tell that your are using the very same statement every time, instead it will need to parse the statement and explicitely check against all it's cached statements. If you put your statement inside the database, the DBMS has the chance to compile the statement and use a mechanism where it does not need to check any statement cache because it knows that this statement is the same. It's the difference between an interpreted language and a compiled language if you will.